views:

81

answers:

3
Class Model<T>{

   private T t;

   .....


   private void someMethod(){
       //now t is null
       Class c = t.getClass();
   } 

   .....

}

Of course it throws NPE.

Class c = t.getClass();

What syntax should i use to get class of T if my instance is null? Is it possible?

+6  A: 

It's not possible due to type erasure.

There is the following workaround:

class Model<T> { 

    private T t; 
    private Class<T> tag;

    public Model(Class<T> tag) {
       this.tag = tag;
    }

    private void someMethod(){ 
       // use tag
    }  
} 
axtavt
A: 

T.class ? As noted in comment above, you can't call anything on the instance (the instance doesn't exist); but you do know it's of type T, right?

M1EK
A: 

You can do this with reflection:

Field f = this.getClass().getField("t");
Class tc = f.getType();
Johnco
It wouldn't work. `tc` would be `Object`
axtavt