21

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?

Community
  • 1
  • 1
Jason
  • 13,563
  • 15
  • 74
  • 125
  • can you post what class do you pass to foo as parameter and what do you expect to get? – hoaz Dec 06 '12 at 19:27

3 Answers3

30

You can override getType() to return your type:

new TypeReference<T>(){
    @Override
    public Type getType() {
        return valueType;
    }
}; 
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
6

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.

StaxMan
  • 113,358
  • 34
  • 211
  • 239
1

I want to convert a Class object to a TypeReference object.

It may be possible to do this, but I cannot think of any realistic problem that it solves. Consider this info from the TypeReference javadoc

This class is used to pass full generics type information, and avoid problems with type erasure (that basically removes most usable type references from runtime Class objects).

My interpretation of this is the only time you would use TypeReference instead of Class is when you need more type information that a Class object can provide. So even if you can figure out how to do this conversion - what have you gained? There is no way to put back erased type information from a Class into a TypeReference.

Any time I have a situation where I need a TypeReference instead of Class, I create a concrete type reference instance and pass that object at run time. Something like this (may not compile, but you get the idea)

foo(TypeReference<T> refArg)
{
   TypeReference<T> ref = refArg; 
}

// later on
object.foo(new TypeReference<List<Set<MyObject>>(){});
Guido Simone
  • 7,912
  • 2
  • 19
  • 21
  • 10
    It allows me to offer support for both methods without having to rewrite every function – Jason Dec 06 '12 at 20:26