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?

Max
  • 2,293
  • 5
  • 32
  • 48
  • If your instance is null, how would t have a class type? – froadie Feb 08 '10 at 16:54
  • 2
    It's not possible, to the best of my knowledge. Remember, Generics are compile-time, not runtime. A more common way to deal with this would be to store a Class object that keeps the class (if you really need it). – Kylar Feb 08 '10 at 16:58
  • A agree with, Kylar and froadie: you need to add an extra check for non-null value for "t". – dma_k Feb 08 '10 at 17:53

3 Answers3

7

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
  • 239,438
  • 41
  • 511
  • 482
-1

You can do it without passing in the class:

class Model<T> {
  Class<T> c = (Class<T>) DAOUtil.getTypeArguments(Model.class, this.getClass()).get(0);
}

You need two functions from this file: http://code.google.com/p/hibernate-generic-dao/source/browse/trunk/dao/src/main/java/com/googlecode/genericdao/dao/DAOUtil.java

For more explanation: http://www.artima.com/weblogs/viewpost.jsp?thread=208860

Peter Tseng
  • 13,613
  • 4
  • 67
  • 57
-1

You can do this with reflection:

Field f = this.getClass().getField("t");
Class tc = f.getType();
Johnco
  • 4,037
  • 4
  • 34
  • 43