How to get generic's class

前端 未结 3 1501
南方客
南方客 2020-12-19 18:52
Class Model{

   private T t;

   .....


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

   .....

}


        
相关标签:
3条回答
  • 2020-12-19 19:11

    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 讨论(0)
  • 2020-12-19 19:14

    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
        }  
    } 
    
    0 讨论(0)
  • 2020-12-19 19:22

    You can do this with reflection:

    Field f = this.getClass().getField("t");
    Class tc = f.getType();
    
    0 讨论(0)
提交回复
热议问题