Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get "Class" object from generic type T

Tags:

java

generics

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?
   .......
}
like image 524
WelcomeTo Avatar asked May 29 '12 13:05

WelcomeTo


People also ask

How do I get a class instance of generic type T?

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.

What does T stand for in generics?

< 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.

How do you pass a generic Object in Java?

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

What does the T designator indicate in a generic class?

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.


1 Answers

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.

like image 62
biziclop Avatar answered Sep 18 '22 15:09

biziclop