0

I have this class

class X<T>{
    public T dowhatever(){
         //jackson parsing
         ObjectMapper mapper = new ObjectMapper();
         T obj = mapper.readValue(jsonString, T);
         return obj;
    }
}

But apparently, I can't pass T to the readValue method. I need a class information. Is there a way to generalize it without passing the Class object as a paremeter?

p.s: I have omitted unnecessary code and left what is relevant.

Em Ae
  • 8,167
  • 27
  • 95
  • 162
  • Basically this is not possible, or at least really really difficult, without the class literal. C.f. here: http://stackoverflow.com/questions/2390662/java-how-do-i-get-a-class-literal-from-a-generic-type – markspace Feb 11 '16 at 01:43

2 Answers2

0

The only way to generalize it is through a sub-class with a specific class as the generic

class MyX extends X<Type> {

You can obtain the Type at runtime as this has to be available for the compiler to check.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

Try this

class X<T> {
    @SuppressWarnings("unchecked")
    public void dowhatever(T... dummy){
        Class<T> classT = (Class<T>)dummy.getClass().getComponentType();
        System.out.println(classT);
    }
}

class Person { }

and

X<Person> x = new X<>();
x.dowhatever(/* no arguments */); // -> class Person 

Or you can get the class object in constructor.

class X<T> {

    private final Class<T> classT;

    @SuppressWarnings("unchecked")
    public X(T... dummy) {
        classT = (Class<T>)dummy.getClass().getComponentType();
    }
}