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?
You can create an instance of TypeReference as: List<String> l1 = new TypeReference<ArrayList<String>>() {}. newInstance();
public class TypeReference extends Object. A reference to a type appearing in a class, field or method declaration, or on an instruction.
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.
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 .
You can override getType()
to return your type:
new TypeReference<T>(){ @Override public Type getType() { return valueType; } };
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
.
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