Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unmarshal XML using generics in Java

I have some packages with POJOs for unmarhsalling. I want to make a generic method where you can pass what kind of class you will unmarhsall it to.

For example:

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

I get an error on the line pointed out in the above code: Illegal class literal for the type parameter E. E would, of course, be from a list of POJOs that actually exist.

How would I accomplish this?

like image 848
syy Avatar asked Mar 13 '23 03:03

syy


1 Answers

You can't do E.class since generics are erased when you compile (turned into type Object, look into type erasure). It's illegal because generic type data isn't accessible at runtime.

Instead, you could allow the developer to pass the class literal via the constructor, store it in the field, then use that:

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

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

    public void unmarshall(String xmlString) {
        //...
        jaxbContext = JAXBContext.newInstance(type);
    }
}

The developer could then do:

new Test<SomeType>(SomeType.class);
like image 114
Vince Avatar answered Mar 20 '23 06:03

Vince