简体   繁体   English

Java-实例化泛型类型的类

[英]Java - Instantiating generic typed class

I have a class for example 我有一个课

public class Example<T> {...}

I would like to instantiate class Example with a specific type class which I know. 我想用我知道的特定类型类实例化类Example。 Pseudocode would look something like that 伪代码看起来像这样

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

So that this would give me same result 这样才能给我同样的结果

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

Is it possible in Java? Java可能吗?

Since, the return type ie 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 而是,将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;
    }
}

Now, here's how you would create generic Example instances. 现在,这是创建通用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM