2

例如,我有一堂课

public class Example<T> {...}

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

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中可能吗?

4

1 回答 1

1

Since, the return type i.e. the class of the new instance is fixed; there's no need to pass it to the method. Instead, add a static factory method to your Example class as

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;
    }
}

Now, here's how you would create generic Example instances.

// 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
于 2013-09-13T15:55:24.217 回答