在 Java 中使用泛型解组 XML
Unmarshal XML using generics in Java
我有一些带有 POJO 的包用于解组。我想创建一个通用方法,您可以在其中传递要解组的 class 类型。
例如:
public class Test<E>
{
E obj;
// Get all the tags/values from the XML
public void unmarshalXML(String xmlString) {
//SomeClass someClass;
JAXBContext jaxbContext;
Unmarshaller unmarshaller;
StringReader reader;
try {
jaxbContext = JAXBContext.newInstance(E.class); // This line doesn't work
unmarshaller = jaxbContext.createUnmarshaller();
reader = new StringReader(xmlString);
obj = (E) unmarshaller.unmarshal(reader);
} catch(Exception e) {
e.printStackTrace();
}
}
}
我在上面代码中指出的行上得到一个错误:Illegal class literal for the type parameter E
。 E
当然,来自实际存在的 POJO 列表。
我将如何做到这一点?
你不能这样做 E.class
因为泛型在你编译时被删除(变成对象类型,查看 type erasure)。这是非法的,因为在运行时无法访问通用类型数据。
相反,您可以允许开发人员通过构造函数传递 class 文字,将其存储在字段中,然后使用:
class Test<E> {
private Class<E> type;
public Test(Class<E> type) {
this.type = type;
}
public void unmarshall(String xmlString) {
//...
jaxbContext = JAXBContext.newInstance(type);
}
}
开发者可以这样做:
new Test<SomeType>(SomeType.class);
我有一些带有 POJO 的包用于解组。我想创建一个通用方法,您可以在其中传递要解组的 class 类型。
例如:
public class Test<E>
{
E obj;
// Get all the tags/values from the XML
public void unmarshalXML(String xmlString) {
//SomeClass someClass;
JAXBContext jaxbContext;
Unmarshaller unmarshaller;
StringReader reader;
try {
jaxbContext = JAXBContext.newInstance(E.class); // This line doesn't work
unmarshaller = jaxbContext.createUnmarshaller();
reader = new StringReader(xmlString);
obj = (E) unmarshaller.unmarshal(reader);
} catch(Exception e) {
e.printStackTrace();
}
}
}
我在上面代码中指出的行上得到一个错误:Illegal class literal for the type parameter E
。 E
当然,来自实际存在的 POJO 列表。
我将如何做到这一点?
你不能这样做 E.class
因为泛型在你编译时被删除(变成对象类型,查看 type erasure)。这是非法的,因为在运行时无法访问通用类型数据。
相反,您可以允许开发人员通过构造函数传递 class 文字,将其存储在字段中,然后使用:
class Test<E> {
private Class<E> type;
public Test(Class<E> type) {
this.type = type;
}
public void unmarshall(String xmlString) {
//...
jaxbContext = JAXBContext.newInstance(type);
}
}
开发者可以这样做:
new Test<SomeType>(SomeType.class);