我有一个泛型课,Foo<T>.在一个方法中Foo,我想得到类型为T的类实例,但我无法调用T.class.
使用它的首选方法是什么T.class?
假设我有一个参数化的Java类,其中包含一个私有的T _member.我想写一个默认的构造函数(没有参数),它以某种方式将我的T _member初始化为一些已知的类型T特定值(对于Integer为-1,对于Float为Float.MAX_VALUE ...).那可能吗?我尝试了新的T(),但编译器不喜欢这样.或者我什么都不做,保证为我调用默认构造函数?
我正在尝试通过JAXB创建一个用于去/序列化的泛型类.在创建JAXBContext类时必须传入,但当然使用泛型类,这是事先不知道的.
所以当我尝试这个时,我当然会得到一个编译错误.
public class ServerSerializing<T>
{
private JAXBContext mJAXBContext = null;
public JAXBContext getJAXBContext()
{
if(mJAXBContext == null)
mJAXBContext = JAXBContext.newInstance(T.class);
return mJAXBContext;
}
}
Run Code Online (Sandbox Code Playgroud)
结果是:
Illegal class literal for the type parameter T
Run Code Online (Sandbox Code Playgroud)
那么通过通用方法可以做到这一点吗?