【问题标题】:Unmarshal XML using generics in Java在 Java 中使用泛型解组 XML
【发布时间】:2016-05-31 19:07:51
【问题描述】:

我有一些带有 POJO 的包用于解组。我想创建一个通用方法,您可以在其中传递您将解组到的类。

例如:

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 EE 当然会来自实际存在的 POJO 列表。

我将如何做到这一点?

【问题讨论】:

    标签: java xml generics unmarshalling


    【解决方案1】:

    你不能做E.class,因为泛型在你编译时会被删除(变成Object类型,查看type erasure)。这是非法的,因为在运行时无法访问泛型类型数据。

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

    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);
    

    【讨论】:

    • 我假设reader = ... 下面的行是type = (Class&lt;E&gt;) unmarshaller.unmarshal(reader);?
    • @Flow 不。你仍然会使用obj = (E) unmarshaller.unmarshal(reader)。您不应该删除 E obj 字段,因为这是存储未编组数据的地方。这意味着您应该有 2 个字段:typeobj
    • 哦,我明白了。非常感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 2018-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-30
    • 2021-12-01
    • 2018-11-07
    • 1970-01-01
    相关资源
    最近更新 更多