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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With