我创建了一个通用的JAXB序列化类,如下所示:
public class JAXBSerializing<T>
implements IXMLSerializing<T>
{
private final Class<T> mType;
public JAXBSerializing(Class<T> oType)
{
mType = oType;
}
}
现在在我的代码中,当我用“普通”类实例化它时,它工作正常。
IXMLSerializing<String>strser = new JAXBSerializing<String>(String.class);
但是当我尝试使用泛型类时,我遇到编译器错误:
MapEntry<String, String>e = new MapEntry<String, String>("Key", "Value");
IXMLSerializing<MapEntry<String, String>>serializer = new JAXBSerializing<MapEntry<String, String>>(MapEntry.class);
我尝试了各种组合,但都没有。
IXMLSerializing<MapEntry<String, String>>serializer = new JAXBSerializing<MapEntry<String, String>>(MapEntry<String, String>.class);
Syntax error on token ">", void expected after this token
或
IXMLSerializing<MapEntry<String, String>>serializer = new JAXBSerializing<MapEntry<String, String>>(MapEntry.class);
The constructor JAXBSerializing<MapEntry<String,String>>(Class<MapEntry>) is undefined
唯一可行的是当我实例化这样的虚拟对象时:
MapEntry<String, String>e = new MapEntry<String, String>("Key", "Value");
IXMLSerializing<MapEntry<String, String>>serializer = new JAXBSerializing<MapEntry<String, String>>((Class<MapEntry<String, String>>) e.getClass());
虽然这有效,但我想知道如何在不使用虚拟对象的情况下将类正确地作为参数传递。即便如此,由于不必要的强制转换,我得到一个未经检查的类型警告,尽管对象都是正确的类型。
答案 0 :(得分:1)
您可以在构造函数上删除type参数并禁止显示警告
public JAXBSerializing(Class<?> oType)
{
mType = oType;
}
然后这不应该产生编译器错误
IXMLSerializing<MapEntry<String, String>> serializer = new JAXBSerializing<MapEntry<String, String>>(MapEntry.class);