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 from T?
public <T> readXmlToObject(String xmlFileName, T jaxbClass) {
JAXBContext context = JAXBContext.newInstance(T.class); // T.class - here error, how to get it?
.......
}
The short answer is, that there is no way to find out the runtime type of generic type parameters in Java. A solution to this is to pass the Class of the type parameter into the constructor of the generic type, e.g.
< T > is a conventional letter that stands for "Type", and it refers to the concept of Generics in Java. You can use any letter, but you'll see that 'T' is widely preferred. WHAT DOES GENERIC MEAN? Generic is a way to parameterize a class, method, or interface.
Generics Work Only with Reference Types: When we declare an instance of a generic type, the type argument passed to the type parameter must be a reference type. We cannot use primitive data types like int, char. Test<int> obj = new Test<int>(20);
Its instances (only one per type exists) are used to represent classes and interfaces, therefore the T in Class<T> refers to the type of the class or interface that the current instance of Class represents.
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.
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