开发者

How to get generic's class

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?


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
    }  
} 


You can do this with reflection:

Field f = this.getClass().getField("t");
Class tc = f.getType();


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜