实例化泛型对象
在你发布的代码中,不可能创建一个泛型T
,因为你不知道它是什么类型:
public class Abc<T>
{
public T getInstanceOfT()
{
// There is no way to create an instance of T here
// since we don't know its type
}
}
当然,如果你有一个引用Class<T>
并且T
有一个默认的构造函数,就可以调用newInstance()
这个Class对象。
如果你继承子类,Abc<T>
你甚至可以解决类型擦除问题,并且不必传递任何Class<T>
引用:
import java.lang.reflect.ParameterizedType;
public class Abc<T>
{
private T getInstanceOfT()
{
ParameterizedType superClass = (ParameterizedType) getClass().getGenericSuperclass();
Class<T> type = (Class<T>) superClass.getActualTypeArguments()[0];
try
{
return type.newInstance();
}
catch (Exception e)
{