有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java创建给定类的实例

在GWT中,我有一个泛型Class<T>,我想在其中动态实例化一个T

class MyGenericClass<T> {

  void foo(Class<T> clazz) {

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

}

但我有以下编译错误:

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

那么如何实例化这个类呢

在另一个线程中,我发现:

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

但是我没有用这个实例化方法找到一个名为Reflection的类


共 (1) 个答案

  1. # 1 楼答案

    create方法的java文档说明了这一切

    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)

    简而言之,不能动态创建实例,必须在编译时静态地知道类类型

    GWT.create(YourClass.class)