在 Java 中实例化一个泛型类 [英] Instantiating a generic class in Java
问题描述
我知道 Java 的泛型比 .Net 的要差一些.
I know Java's generics are somewhat inferior to .Net's.
我有一个通用类 Foo
,我真的需要使用无参数构造函数在 Foo
中实例化一个 T
.如何解决 Java 的局限性?
I have a generic class Foo<T>
, and I really need to instantiate a T
in Foo
using a parameter-less constructor. How can one work around Java's limitation?
推荐答案
一个选项是传入 Bar.class
(或您感兴趣的任何类型 - 指定适当的Class
引用)并将该值保留为字段:
One option is to pass in Bar.class
(or whatever type you're interested in - any way of specifying the appropriate Class<T>
reference) and keep that value as a field:
public class Test {
public static void main(String[] args) throws IllegalAccessException,
InstantiationException {
Generic<Bar> x = new Generic<>(Bar.class);
Bar y = x.buildOne();
}
}
public class Generic<T> {
private Class<T> clazz;
public Generic(Class<T> clazz) {
this.clazz = clazz;
}
public T buildOne() throws InstantiationException, IllegalAccessException {
return clazz.newInstance();
}
}
public class Bar {
public Bar() {
System.out.println("Constructing");
}
}
另一种选择是拥有一个工厂"接口,并将工厂传递给泛型类的构造函数.这样更灵活,您无需担心反射异常.
Another option is to have a "factory" interface, and you pass a factory to the constructor of the generic class. That's more flexible, and you don't need to worry about the reflection exceptions.
这篇关于在 Java 中实例化一个泛型类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!