I want to make generic function that return Object representation of XML document (using JAXB). I need to pass \"class\" object to JAXBContext constructor, but how I can get it
Take a look at this SO answer.
Basically, the type T isn't available at runtime - Java generics are subject to erasure by the compiler.
Fortunately you already have an instance of your class, so you can get the type information from there:
public <T> readXmlToObject(String xmlFileName, T jaxbClass) {
// if jaxbClass is an instance of the data object, you can do this:
JAXBContext context = JAXBContext.newInstance(jaxbClass.getClass());
// alternatively if jaxbClass is an instance of the Class object:
JAXBContext context = JAXBContext.newInstance(jaxbClass);
// ......
}
try to pass the class itself, something like this
public <T> readXmlToObject(String xmlFileName, Class<T> class) {
public class XYZ<T> {
...
private Class<T> tClass;
...
public <T> readXmlToObject(String xmlFileName) {
JAXBContext context = JAXBContext.newInstance(tClass);
...
}
...
}
Pass the class object instead and it's easy.
public <T> T readXmlToObject(String xmlFileName, Class<T> jaxbClass) {
JAXBContext context = JAXBContext.newInstance( jaxbClass ); // T.class - here error, how to get it?
Object o = context.createUnmarshaller().unmarshal( new File( xmlFileName ) );
return jaxbClass.cast( o );
}
The idea here is that since you can't extract the type parameter from the object, you have to do it the other way around: start with the class and then manipulate the object to match the type parameter.
You cannot get the class of at run time. Java implements Generics using Type Safe Erasure which means that the understanding of the Generic type is only applied at up through compilation. You must interogate the actual object at run time if you want to get its class.
Don't listen to the others... you CAN get it.
Simply change the type of the jaxbClass
parameter to Class<T>
:
public <T> T readXmlToObject(String xmlFileName, Class<T> jaxbClass) {
JAXBContext context = JAXBContext.newInstance(jaxbClass);
.......
}