Arnaud Denoyelle
Arnaud Denoyelle

Reputation: 31283

Create an instance of a given class

In GWT, I have a a generic Class<T> in which I want to dynamically instantiate a T :

class MyGenericClass<T> {

  void foo(Class<T> clazz) {

    ...
    T t = GWT.create(clazz); //I want to instantiate T
  }

}

But I have the following compile error :

Only class literals may be used as arguments to GWT.create()

So how do I instantiate this class?

In another thread I found :

GWT.create( Reflection.class ).instantiate( YourClass.class );

But I did not find a class called Reflection with this instantiate method.

Upvotes: 3

Views: 256

Answers (1)

user1339772
user1339772

Reputation: 803

The java doc of create method says it all

The argument to create(Class) must be a class literal because the Production Mode compiler must be able to statically determine the requested type at compile-time. This can be tricky because using a Class variable may appear to work correctly in Development Mode.

http://www.gwtproject.org/javadoc/latest/com/google/gwt/core/client/GWT.html#create(java.lang.Class)

In short you cannot dynamically create instance, the class type must be statically know at compile time.

GWT.create(YourClass.class)

Upvotes: 1

Related Questions