Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert from Class<T> to TypeReference<T>

Tags:

Basically just the opposite of this question. I want to convert a Class<T> object to a TypeReference<T> object.

I have tried:

foo(Class<T> valueType) {    TypeReference ref = new TypeReference<T>(){};  } 

but that just returns a type reference of the classes's super class. I also tried:

foo(Class<T> valueType) {    TypeReference ref = new TypeReference<valueType>(){};  } 

and

foo(Class<T> valueType) {    TypeReference ref = new TypeReference<valueType.getRawClass()>(){};  } 

But the second two don't compile. How do I do this?

like image 764
Jason Avatar asked Dec 06 '12 19:12

Jason


People also ask

How do you create TypeReference?

You can create an instance of TypeReference as: List<String> l1 = new TypeReference<ArrayList<String>>() {}. newInstance();

What is a TypeReference in Java?

public class TypeReference extends Object. A reference to a type appearing in a class, field or method declaration, or on an instruction.

What is the use of TypeReference?

Creates and instance of TypeReference<T> which maintains the generic T of the passed Class. This method will cache the instance of TypeReference<T> using the passed Class as the key. This is meant to be used with non-generic types such as primitive object types and POJOs, not Map or List parameterized types.

How do I pass TypeReference in Java?

You can use JAVA generics. One way is to allow all class types to be acceptable, by this.. or a better way would be to make all classes you want to be accepted derive from an interface, say Person and then you can do.. This limits the set of classes accepted by the the method, to only those implementing Person .


2 Answers

You can override getType() to return your type:

new TypeReference<T>(){     @Override     public Type getType() {         return valueType;     } };  
like image 68
SLaks Avatar answered Nov 15 '22 11:11

SLaks


As others have pointed out, you may well be solving wrong problem. What you may want to unify towards is actually JavaType, because that is what both of your inputs get converted to, and that is what Jackson internally uses for everything. And then you can have convenience methods to get to JavaType.

like image 40
StaxMan Avatar answered Nov 15 '22 10:11

StaxMan