【问题标题】:Java - Instantiating generic typed classJava - 实例化泛型类型类
【发布时间】:2013-09-18 08:49:23
【问题描述】:

例如,我有一堂课

public class Example<T> {...}

我想用我知道的特定类型类实例化类 Example。伪代码看起来像这样

public Example<T> createTypedExample(Class exampleClass, Class typeClass) {
  exampleClass.newInstance(typeClass); // made-up
}

所以这会给我同样的结果

Example<String> ex = new Example<String>();
ex = createTypedExample(Example.class, String.class);

在 Java 中可以吗?

【问题讨论】:

  • @VirtualTroll 他想将它作为类型参数传递。不要在上面调用构造函数。
  • 我实际上认为这是不可能的。 Java 在编译时做一些通用的事情。

标签: java generics reflection types instance


【解决方案1】:

因为,返回类型,即新实例的类是固定的;无需将其传递给方法。相反,将static 工厂方法添加到您的Example 类中

public class Example<T> {

    private T data;

    static <T> Example<T> newTypedExample(Class<T> type) {
        return new Example<T>();
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}

现在,这是创建通用 Example 实例的方法。

// String
Example<String> strTypedExample = Example.newTypedExample(String.class);

strTypedExample.setData("String Data");
System.out.println(strTypedExample.getData()); // String Data

// Integer
Example<Integer> intTypedExample = Example.newTypedExample(Integer.class);

intTypedExample.setData(123);
System.out.println(intTypedExample.getData()); // 123

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-03
    • 2011-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多