使用Java中的泛型解组XML

syy*_*syy 3 java xml generics unmarshalling

我有一些POJO包用于unmarhsalling.我想创建一个通用的方法,你可以传递你将无法解决的类.

例如:

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我在上面的代码中指出的行上得到一个错误:Illegal class literal for the type parameter E.E当然,它将来自实际存在的POJO列表.

我怎么做到这一点?

Vin*_*igh 6

你无法做到,E.class因为编译时会删除泛型(转换为类型Object,查看类型擦除).这是非法的,因为在运行时无法访问泛型类型数据.

相反,您可以允许开发人员通过构造函数传递类文字,将其存储在字段中,然后使用:

class Test<E> {
    private Class<E> type;

    public Test(Class<E> type) {
        this.type = type;
    }

    public void unmarshall(String xmlString) {
        //...
        jaxbContext = JAXBContext.newInstance(type);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后开发人员可以:

new Test<SomeType>(SomeType.class);
Run Code Online (Sandbox Code Playgroud)