Is there a way to fix the warning related to the support of string-based lookup for the factory? - system-verilog

I often get this warning message:
UVM_WARNING # 0: reporter [TPRGED] Type name 'packet2mem_comp_Str' already registered with factory. No string-based lookup support for multiple types with the same type name.
I did not register any class with the same name, unless the parent one which, I suppose, does not present any problem.
My class is an inherited parametrized class declared as follows:
class packet2mem_comp #(string S = "MEM") extends mem_comp;
typedef packet2mem_comp #(S) packet2mem_comp_Str;
`uvm_object_utils(packet2mem_comp_Str)
function new (string name = "packet2mem_comp");
super.new(name);
endfunction : new
... //rest of my code
endclass: packet2mem_comp
Does anyone know how to fix this warning?

There are special versions of the macros for parameterised classes. Instead of
`uvm_object_utils(packet2mem_comp_Str)
try
`uvm_object_param_utils(packet2mem_comp_Str)
or perhaps
`uvm_object_param_utils(packet2mem_comp #(S))
You have not posted an MCVE, so I have not tested this.

Related

ovm printer casting error

I wanted to print out a structure used in a ovm_sequence_item. Since the structure is long, I plan to override table printer knobs by using tbl_printer.knobs.value_width = 100;
Here is the code snipper
virtual function void do_print(ovm_printer printer);
ovm_table_printer tbl_printer;
super.do_print(printer); //print all other fields
$cast(tbl_printer, printer);
tbl_printer.knobs.value_width = 100;
tbl_printer.print_generic("ppid","CppPpid_t",$bits(CppPpid_t),
$psprintf("A=%0b,B=%0b,C=%0d,D=%0d,E=%0d,F=%0x",
struct.A,
struct.B,
struct.C,
struct.D,
struct.E,
struct.F)
);
endfunction: do_print
I am getting this casting error.
Error-[DCF] Dynamic cast failed
*.sv, 58
Casting of source class type 'SIP_SHARED_LIB.ovm_pkg.ovm_tree_printer' to
destination class type 'SIP_SHARED_LIB.ovm_pkg.ovm_table_printer' failed due
to type mismatch.
Please ensure matching types for dynamic cast
Can someone help me what I am doing wrong? How is it getting ovm_tree_printer when I am trying to use ovm_printer?
ovm_printer is just the base class that declares the API for printers. What gets passed around are concrete classes, like ovm_table_printer or ovm_tree_printer. Both of these can be stored in a variable of type ovm_printer.
You're probably passing a tree printer in the print(...) call on your object. If you don't specify any printer, the default printer is used. Per default, this is the table printer, but it could be that this was changed. Look for ovm_default_printer in the package scope.
If someone explicitly wants you to do a tree print, then you can't magically change that to a table print. Best you can do is check if you're doing a table print and if so then change the knobs:
if (!$cast(tbl_printer, printer))
return;
tbl_printer.knobs.value_width = 100;

UVM- run test() in top block and Macros

I'm reading the following guide:
https://colorlesscube.com/uvm-guide-for-beginners/chapter-3-top-block/
In Code 3.2 line 24- run_test();
I realized that it supposed to execute the test, but how it know which test, and how, and why should I write it in the top block.
In Code 4.1 lines 11-14 (https://colorlesscube.com/uvm-guide-for-beginners/chapter-4-transactions-sequences-and-sequencers/):
`uvm_object_utils_begin(simpleadder_transaction)
`uvm_field_int(ina, UVM_ALL_ON)
`uvm_field_int(inb, UVM_ALL_ON)
`uvm_field_int(out, UVM_ALL_ON)
`uvm_object_utils_end
Why should I add the "uvm_field_int" , what would happend if i didn't add them, and what is "UVM_ALL_ON"?
run_test is a helper global function , it calls the run_test function of the uvm_root class to run the test case. There are two ways by which you can pass the test name to the function.The first is via the function argument and the second is via a command line argument. The command line argument takes precedence over the test name passed via the function argument.
+UVM_TESTNAME=YOUR_TEST_NAME
run_test("YOUR_TEST_NAME");
run_test function in the uvm_root uses the factory mechanism to create the appropriate instance of the umm_test class and so the test case must register itself with the factory using the macro `uvm_component_utils for the factory mechanism (create_component_by_name) to function.
class YOUR_TEST_NAME extends umm_test ;
// register the class with the factory
// so that run_test can find this class when the
// string test_name is passed to it.
`uvm_component_utils(YOUR_TEST_NAME)
.....
endclass
The run_test function then kicks of the uvm_phases (..,build_phase,connect_phase,...) starting the uvm portion of the simulation. There should be no time ticks consumed before the run_phase starts , so it is essential that run_test case is called in the initial block itself. Also we want the uvm and test bench to be ready to drive and receive data as soon as the RTL is ready for which it is essential that we start the run_test at the earliest. Any delay in doing so will generate an error.
`uvm_field_int/uvm_field_object/.. are called field automation macros. They are not mandatory in the class definition and are provided as a helper macros to ease the use of many common/routine functions of the uvm_object. Examples of thse functions in uvm_object are - copy,compare,pack,unpack,print, etc and these macros generate code to automatically use these functions.
If you are not using the uvm_object common functions leaving out these macros from the class definition will not produce any errors.
In case you implement you own version of the common operations you can also leave out these macros from the class.
UVM_ALL_ON - enables all functions like compare/copy/... to be implemented for the particular field.
link with examples -
http://www.testbench.in/UT_04_UVM_TRANSACTION.html
For example the uvm_object has a compare function which compare two instances of the same class and return true if all the variables in the class are equal.
virtual function bit do_compare( uvm_object rhs, uvm_comparer comparer );
.....
// return 1 if all the variables match
return ( super.do_compare( rhs, comparer ) &&
this.var_1 == rhs.var_1 &&
this.var_2 == rhs.var_2 &&
......
this.var_n == rhs.var_n );
endfunction: do_compare
// use in main code
if ( new_class.compare(old_classs) )
...
//instead of
if ( new_class.var1 == old_class.var1 && new_class.var2 == old_class.var2 && ... new_class.varn == old_class.varn )
...
The above compare has to be written for each class and updated and maintained for every new variable that is added to the class. This could become error prone as newer variables are added. A similar process has to be followed for all the standard functions uvm_object provides.
The field automation macro generates function to address all these functionality automatically. So doing a do_print for a class with the macros will print out all the fields without explicitly writing any code for it.
// compare/print/.. functions for class simpleadder_transaction are provided by using `uvm_field_int macro.
`uvm_object_utils_begin(simpleadder_transaction)
`uvm_field_int(ina, UVM_ALL_ON)
`uvm_object_utils_end
BUT a word of caution , the use of these macros are discouraged as they add a significant amount of code into the class.. Most of these functions may not be needed by the class yet they get generated by default.
run_test is defined in the documentation (link) as:
virtual task run_test (
string test_name = ""
)
So, in principle, you can state there the test name as a string. But what's usually done is to pass it in the command line of your simulator using the argument: +UVM_TESTNAME=TEST_NAME
The uvm_object macros are a bit more complicated. They generate several methods and more importantly they register the object in the UVM factory, which is what makes them necessary (at least if you are using, as you should, the factory to create them). Citing from the UVM Class Reference documentation (Section 20.2 Component and Object Macros):
Simple (non-parameterized) objects use the uvm_object_utils* versions,
which do the following:
Implements get_type_name, which returns TYPE as a string
Implements create, which allocates an object of type TYPE by calling its constructor with no arguments. TYPE’s constructor, if
defined, must have default values on all it arguments.
Registers the TYPE with the factory, using the string TYPE as the factory lookup string for the type.
Implements the static get_type() method which returns a factory proxy object for the type.
Implements the virtual get_object_type() method which works just like the static get_type() method, but operates on an already
allocated object.

How can I fake a Class used insite SUT using FakeItEasy

Am having a little trouble understanding what and what cannot be done using FakeItEasy. Suppose I have a class
public class ToBeTested{
public bool MethodToBeTested(){
SomeDependentClass dependentClass = new SomeDependentClass();
var result = dependentClass.DoSomething();
if(result) return "Something was true";
return "Something was false";
}
}
And I do something like below to fake the dependent class
var fakedDepClass = A.Fake<DependentClass>();
A.CallTo(fakedDepClass).WithReturnType<bool>().Returns(true);
How can i use this fakedDepClass when am testing MethodToBeTested. If DependentClass was passed as argument, then I can pass my fakedDepClass, but in my case it is not (also this is legacy code that I dont control).
Any ideas?
Thanks
K
Calling new SomeDependentClass() inside MethodToBeTested means that you get a concrete actual SomeDependentClass instance. It's not a fake, and cannot be a FakeItEasy fake.
You have to be able to inject the fake class into the code to be tested, either (as you say) via an argument to MethodToBeTested or perhaps through one of ToBeTested's constructors or properties.
If you can't do that, FakeItEasy will not be able to help you.
If you do not have the ability to change ToBeTested (and I'd ask why you're writing tests for it, but that's an aside), you may need to go with another isolation framework. I have used TypeMock Isolator for just the sort of situation you describe, and it did a good job.

How many constructors should a class have?

I'm currently modifying a class that has 9 different constructors. Now overall I believe this class is very poorly designed... so I'm wondering if it is poor design for a class to have so many constructors.
A problem has arisen because I recently added two constructors to this class in an attempt to refactor and redesign a class (SomeManager in the code below) so that it is unit testable and doesn't rely on every one of its methods being static. However, because the other constructors were conveniently hidden out of view about a hundred lines below the start of the class I didn't spot them when I added my constructors.
What is happening now is that code that calls these other constructors depends on the SomeManager class to already be instantiated because it used to be static....the result is a null reference exception.
So my question is how do I fix this issue? By trying to reduce the number of constructors? By making all the existing constructors take an ISomeManager parameter?
Surely a class doesn't need 9 constructors! ...oh and to top it off there are 6000 lines of code in this file!
Here's a censored representation of the constructors I'm talking about above:
public MyManager()
: this(new SomeManager()){} //this one I added
public MyManager(ISomeManager someManager) //this one I added
{
this.someManager = someManager;
}
public MyManager(int id)
: this(GetSomeClass(id)) {}
public MyManager(SomeClass someClass)
: this(someClass, DateTime.Now){}
public MyManager(SomeClass someClass, DateTime someDate)
{
if (someClass != null)
myHelper = new MyHelper(someOtherClass, someDate, "some param");
}
public MyManager(SomeOtherClass someOtherClass)
: this(someOtherClass, DateTime.Now){}
public MyManager(SomeOtherClass someOtherClass, DateTime someDate)
{
myHelper = new MyHelper(someOtherClass, someDate, "some param");
}
public MyManager(YetAnotherClass yetAnotherClass)
: this(yetAnotherClass, DateTime.Now){}
public MyManager(YetAnotherClass yetAnotherClass, DateTime someDate)
{
myHelper = new MyHelper(yetAnotherClass, someDate, "some param");
}
Update:
Thanks everyone for your responses...they have been excellent!
Just thought I'd give an update on what I've ended up doing.
In order to address the null reference exception issue I've modified the additional constructors to take an ISomeManager.
At the moment my hands are tied when it comes to being allowed to refactor this particular class so I'll be flagging it as one on my todo list of classes to redesign when I have some spare time. At the moment I'm just glad I've been able to refactor the SomeManager class...it was just as huge and horrible as this MyManager class.
When I get around to redesigning MyManager I'll be looking for a way to extract the functionality into two or three different classes...or however many it takes to ensure SRP is followed.
Ultimately, I haven't come to the conclusion that there is a maximum number of constructors for any given class but I believe that in this particular instance I can create two or three classes each with two or three constructors each..
A class should do one thing and one thing only. If it has so many constructors it seems to be a tell tale sign that it's doing too many things.
Using multiple constructors to force the correct creation of instances of the object in a variety of circumstances but 9 seems like a lot. I would suspect there is an interface in there and a couple of implementations of the interface that could be dragged out. Each of those would likely have from one to a few constructors each relevant to their specialism.
As little as possible,
As many as necessary.
9 constructors and 6000 lines in class is a sign of code smell. You should re-factor that class.
If the class is having lot of responsibilities and then you should separate them out. If the responsibilities are similar but little deviation then you should look to implement inheritance buy creating a interface and different implementations.
If you arbitrarily limit the number of constructors in a class, you could end up with a constructor that has a massive number of arguments. I would take a class with 100 constructors over a constructor with 100 arguments everyday. When you have a lot of constructors, you can choose to ignore most of them, but you can't ignore method arguments.
Think of the set of constructors in a class as a mathematical function mapping M sets (where each set is a single constructor's argument list) to N instances of the given class. Now say, class Bar can take a Foo in one of its constructors, and class Foo takes a Baz as a constructor argument as we show here:
Foo --> Bar
Baz --> Foo
We have the option of adding another constructor to Bar such that:
Foo --> Bar
Baz --> Bar
Baz --> Foo
This can be convenient for users of the Bar class, but since we already have a path from Baz to Bar (through Foo), we don't need that additional constructor. Hence, this is where the judgement call resides.
But if we suddenly add a new class called Qux and we find ourselves in need to create an instance of Bar from it: we have to add a constructor somewhere. So it could either be:
Foo --> Bar
Baz --> Bar
Qux --> Bar
Baz --> Foo
OR:
Foo --> Bar
Baz --> Bar
Baz --> Foo
Qux --> Foo
The later would have a more even distribution of constructors between the classes but whether it is a better solution depends largely on the way in which they are going to be used.
The answer: 1 (with regards to injectables).
Here's a brilliant article on the topic: Dependency Injection anti-pattern: multiple constructors
Summarized, your class's constructor should be for injecting dependencies and your class should be open about its dependencies. A dependency is something your class needs. Not something it wants, or something it would like, but can do without. It's something it needs.
So having optional constructor parameters, or overloaded constructors, makes no sense to me. Your sole public constructor should define your class's set of dependencies. It's the contract your class is offering, that says "If you give me an IDigitalCamera, an ISomethingWorthPhotographing and an IBananaForScale, I'll give you the best damn IPhotographWithScale you can imagine. But if you skimp on any of those things, you're on your own".
Here's an article, by Mark Seemann, that goes into some of the finer reasons for having a canonical constructor: State Your Dependency Intent
It's not just this class you have to worry about re-factoring. It's all the other classes as well. And this is probably just one thread in the tangled skein that is your code base.
You have my sympathy... I'm in the same boat.
Boss wants everything unit tested, doesn't want to rewrite code so we can unit test. End up doing some ugly hacks to make it work.
You're going to have to re-write everything that is using the static class to no longer use it, and probably pass it around a lot more... or you can wrap it in a static proxy that accessses a singleton. That way you an at least mock the singleton out, and test that way.
Your problem isn't the number of constructors. Having 9 constructors is more than usual, but I don't think it is necessarily wrong. It's certainly not the source of your problem. The real problem is that the initial design was all static methods. This is really a special case of the classes being too tightly coupled. The now-failing classes are bound to the idea that the functions are static. There isn't much you can do about that from the class in question. If you want to make this class non-static, you'll have to undo all that coupling that was written into the code by others. Modify the class to be non-static and then update all of the callers to instantiate a class first (or get one from a singleton). One way to find all of the callers is to make the functions private and let the compiler tell you.
At 6000 lines, the class is not very cohesive. It's probably trying to do too much. In a perfect world you would refactor the class (and those calling it) into several smaller classes.
Enough to do its task, but remember the Single Responsibility Principle, which states that a class should only have a single responsibility. With that in mind there are probably very few cases where it makes sense to have 9 constructors.
I limit my class to only have one real constructor. I define the real constructor as the one that has a body. I then have other constructors that just delegate to the real one depending on their parameters. Basically, I'm chaining my constructors.
Looking at your class, there are four constructors that has a body:
public MyManager(ISomeManager someManager) //this one I added
{
this.someManager = someManager;
}
public MyManager(SomeClass someClass, DateTime someDate)
{
if (someClass != null)
myHelper = new MyHelper(someOtherClass, someDate, "some param");
}
public MyManager(SomeOtherClass someOtherClass, DateTime someDate)
{
myHelper = new MyHelper(someOtherClass, someDate, "some param");
}
public MyManager(YetAnotherClass yetAnotherClass, DateTime someDate)
{
myHelper = new MyHelper(yetAnotherClass, someDate, "some param");
}
The first one is the one that you've added. The second one is similar to the last two but there is a conditional. The last two constructors are very similar, except for the type of parameter.
I would try to find a way to create just one real constructor, making either the 3rd constructor delegate to the 4th or the other way around. I'm not really sure if the first constructor can even fit in as it is doing something quite different than the old constructors.
If you are interested in this approach, try to find a copy of the Refactoring to Patterns book and then go to the Chain Constructors page.
Surely a class should have as many constructors as are required by the class... this doesnt mean than bad design can take over.
Class design should be that a constructor creates a valid object after is has finished. If you can do that with 1 param or 10 params then so be it!
It seems to me that this class is used to do way, way to much. I think you really should refactor the class and split it into several more specialized classes. Then you can get rid of all these constructors and have a cleaner, more flexible, more maintainable and more readable code.
This was not at direct answer to your question, but i do believe that if it is necessary for a class to have more than 3-4 constructors its a sign that it probably should be refactored into several classes.
Regards.
The only "legit" case I can see from you code is if half of them are using an obsolete type that you are working to remove from the code. When I work like this I frequently have double sets of constructors, where half of them are marked #Deprecated or #Obsolete. But your code seems to be way beyond that stage....
I generally have one, which may have some default parameters. The constructor will only do the minimum setup of the object so it's valid by the time it's been created. If I need more, I'll create static factory methods. Kind of like this:
class Example {
public:
static FromName(String newname) {
Example* result = new Example();
result.name_ = newname;
return result;
}
static NewStarter() { return new Example(); }
private:
Example();
}
Okay that's not actually a very good example, I'll see if I can think of a better one and edit it in.
The awnser is: NONE
Look at the Language Dylan. Its has a other System.
Instat of a constructors you add more values to your slots (members) then in other language. You can add a "init-keyword". Then if you make a instance you can set the slot to the value you want.
Ofcourse you can set 'required-init-keyword:' and there are more options you can use.
It works and it is easy. I dont miss the old system. Writing constructors (and destructors).
(btw. its still a very fast language)
I think that a class that has more than one constructor has more than one responsibility. Would be nice to be convinced about the opposite however.
A constructor should have only those arguments which are mandatory for creating the instance of that class. All other instance variables should have corresponding getter and setter methods. This will make your code flexible if you plan to add new instance variables in the future.
In fact following OO principle of -
For each class design aim for low coupling and high cohesion
Classes should be open for extension but closed for modification.
you should have a design like -
import static org.apache.commons.lang3.Validate.*;
public class Employee
{
private String name;
private Employee() {}
public String getName()
{
return name;
}
public static class EmployeeBuilder
{
private final Employee employee;
public EmployeeBuilder()
{
employee = new Employee();
}
public EmployeeBuilder setName(String name)
{
employee.name = name;
return this;
}
public Employee build()
{
validateFields();
return employee;
}
private void validateFields()
{
notNull(employee.name, "Employee Name cannot be Empty");
}
}
}

GWT Dynamic loading using GWT.create() with String literals instead of Class literals

GWT.create() is the reflection equivalent in GWT,
But it take only class literals, not fully qualified String for the Class name.
How do i dynamically create classes with Strings using GWT.create()?
Its not possible according to many GWT forum posts but how is it being done in frameworks like Rocket-GWT (http://code.google.com/p/rocket-gwt/wiki/Ioc) and Gwittir (http://code.google.com/p/gwittir/wiki/Introspection)
It is possible, albeit tricky. Here are the gory details:
If you only think as GWT as a straight Java to JS, it would not work. However, if you consider Generators - Special classes with your GWT compiler Compiles and Executes during compilation, it is possible. Thus, you can generate java source while even compiling.
I had this need today - Our system deals with Dynamic resources off a Service, ending into a String and a need for a class. Here is the solutuion I've came up with - btw, it works under hosted, IE and Firefox.
Create a GWT Module declaring:
A source path
A Generator (which should be kept OUTSIDE the package of the GWT Module source path)
An interface replacement (it will inject the Generated class instead of the interface)
Inside that package, create a Marker interface (i call that Constructable). The Generator will lookup for that Marker
Create a base abstract class to hold that factory. I do this in order to ease on the generated source code
Declare that module inheriting on your Application.gwt.xml
Some notes:
Key to understanding is around the concept of generators;
In order to ease, the Abstract base class came in handy.
Also, understand that there is name mandling into the generated .js source and even the generated Java source
Remember the Generator outputs java files
GWT.create needs some reference to the .class file. Your generator output might do that, as long as it is referenced somehow from your application (check Application.gwt.xml inherits your module, which also replaces an interface with the generator your Application.gwt.xml declares)
Wrap the GWT.create call inside a factory method/singleton, and also under GWT.isClient()
It is a very good idea to also wrap your code-class-loading-calls around a GWT.runAsync, as it might need to trigger a module load. This is VERY important.
I hope to post the source code soon. Cross your fingers. :)
Brian,
The problem is GWT.create doen't know how to pick up the right implementation for your abstract class
I had the similar problem with the new GWT MVP coding style
( see GWT MVP documentation )
When I called:
ClientFactory clientFactory = GWT.create(ClientFactory.class);
I was getting the same error:
Deferred binding result type 'com.test.mywebapp.client.ClientFactory' should not be abstract
All I had to do was to go add the following lines to my MyWebapp.gwt.xml file:
<!-- Use ClientFactoryImpl by default -->
<replace-with class="com.test.mywebapp.client.ClientFactoryImpl">
<when-type-is class="com.test.mywebapp.client.ClientFactory"/>
</replace-with>
Then it works like a charm
I ran into this today and figured out a solution. The questioner is essentially wanting to write a method such as:
public <T extends MyInterface> T create(Class<T> clz) {
return (T)GWT.create(clz);
}
Here MyInterface is simply a marker interface to define the range of classes I want to be able to dynamically generate. If you try to code the above, you will get an error. The trick is to define an "instantiator" such as:
public interface Instantiator {
public <T extends MyInterface> T create(Class<T> clz);
}
Now define a GWT deferred binding generator that returns an instance of the above. In the generator, query the TypeOracle to get all types of MyInterface and generate implementations for them just as you would for any other type:
e.g:
public class InstantiatorGenerator extends Generator {
public String generate(...) {
TypeOracle typeOracle = context.getTypeOracle();
JClassType myTYpe= typeOracle.findType(MyInterface.class.getName());
JClassType[] types = typeOracle.getTypes();
List<JClassType> myInterfaceTypes = Collections.createArrayList();
// Collect all my interface types.
for (JClassType type : types) {
if (type.isInterface() != null && type.isAssignableTo(myType)
&& type.equals(myType) == false) {
myInterfaceTypes.add(type);
}
for (JClassType nestedType : type.getNestedTypes()) {
if (nestedType.isInterface() != null && nestedType.isAssignableTo(myType)
&& nestedType.equals(myTYpe) == false) {
myInterfaceTypes.add(nestedType);
}
}
}
for (JClassType jClassType : myInterfaceTypes) {
MyInterfaceGenerator generator = new MyInterfaceGenerator();
generator.generate(logger, context, jClassType.getQualifiedSourceName());
}
}
// Other instantiator generation code for if () else if () .. constructs as
// explained below.
}
The MyIntefaceGenerator class is just like any other deferred binding generator. Except you call it directly within the above generator instead of via GWT.create. Once the generation of all known sub-types of MyInterface is done (when generating sub-types of MyInterface in the generator, make sure to make the classname have a unique pattern, such as MyInterface.class.getName() + "_MySpecialImpl"), simply create the Instantiator by again iterating through all known subtypes of MyInterface and creating a bunch of
if (clz.getName().equals(MySpecialDerivativeOfMyInterface)) { return (T) new MySpecialDerivativeOfMyInterface_MySpecialImpl();}
style of code. Lastly throw an exception so you can return a value in all cases.
Now where you'd call GWT.create(clz); instead do the following:
private static final Instantiator instantiator = GWT.create(Instantiator.class);
...
return instantiator.create(clz);
Also note that in your GWT module xml, you'll only define a generator for Instantiator, not for MyInterface generators:
<generate-with class="package.rebind.InstantiatorGenerator">
<when-type-assignable class="package.impl.Instantiator" />
</generate-with>
Bingo!
What exactly is the question - i am guessing you wish to pass parameters in addition to the class literal to a generator.
As you probably already know the class literal passed to GWT.create() is mostly a selector so that GWT can pick and execute a generator which in the end spits out a class. The easist way to pass a parameter to the generator is to use annotations in an interface and pass the interface.class to GWT.create(). Note of course the interface/class must extend the class literal passed into GWT.create().
class Selector{
}
#Annotation("string parameter...")
class WithParameter extends Selector{}
Selector instance = GWT.create( WithParameter.class )
Everything is possible..although may be difficult or even useless. As Jan has mentioned you should use a generator to do that. Basically you can create your interface the generator code which takes that interface and compile at creation time and gives you back the instance. An example could be:
//A marker interface
public interface Instantiable {
}
//What you will put in GWT.create
public interface ReflectionService {
public Instantiable newInstance(String className);
}
//gwt.xml, basically when GWT.create finds reflectionservice, use reflection generator
<generate-with class="...ReflectionGenerator" >
<when-type-assignable class="...ReflectionService" />
</generate-with>
//In not a client package
public class ReflectionGenerator extends Generator{
...
}
//A class you may instantiate
public class foo implements Instantiable{
}
//And in this way
ReflectionService service = GWT.create(ReflectionService.class);
service.newInstance("foo");
All you need to know is how to do the generator. I may tell you that at the end what you do in the generator is to create Java code in this fashion:
if ("clase1".equals(className)) return new clase1();
else if ("clase2".equals(className)) return new clase2();
...
At the final I thought, common I can do that by hand in a kind of InstanceFactory...
Best Regards
I was able to do what I think you're trying to do which is load a class and bind it to an event dynamically; I used a Generator to dynamically link the class to the event. I don't recommend it but here's an example if it helps:
http://francisshanahan.com/index.php/2010/a-simple-gwt-generator-example/
Not having looked through the code of rocket/gwittir (which you ought to do if you want to find out how they did it, it is opensource after all), i can only guess that they employ deferred binding in such a way that during compile time, they work out all calls to reflection, and statically generate all the code required to implement those call. So during run-time, you cant do different ones.
What you're trying to do is not possible in GWT.
While GWT does a good job of emulating Java at compile time the runtime is of course completely different. Most reflection is unsupported and it is not possible to generate or dynamically load classes at runtime.
I had a brief look into code for Gwittir and I think they are doing their "reflection stuff" at compile time. Here: http://code.google.com/p/gwittir/source/browse/trunk/gwittir-core/src/main/java/com/totsp/gwittir/rebind/beans/IntrospectorGenerator.java
You might be able to avoid the whole issue by doing it on the server side. Say with a service
witch takes String and returns some sort of a serializable super type.
On the server side you can do
return (MySerializableType)Class.forName("className").newInstance();
Depending on your circumstances it might not be a big performance bottleneck.