问题描述
我知道Java的泛型与.Net相比有些逊色。我有一个泛型类 Foo< T>
,我真的需要使用无参数的构造函数在 Foo
中实例化 T
。如何解决Java的限制?
一个选项是传入 Bar.class
(或任何您感兴趣的类型 - 以任何方式指定适当的
Class< T>
引用)并将该值保留为字段:
public class Test
{
public static void main(String [] args)
throws Exception //只是为了简单!
{
通用< Bar> x =新的通用< Bar>(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()抛出InstantiationException,
IllegalAccessException
{
return clazz.newInstance();
public class Bar
{
public Bar()
{
System.out.println(构建);
}
}
另一种选择是有一个工厂并将工厂传递给泛型类的构造函数。这更加灵活,您不必担心反射异常。
I know Java's generics are somewhat inferior to .Net's.
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?
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 Exception // Just for simplicity!
{
Generic<Bar> x = new Generic<Bar>(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中实例化一个泛型类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!