How to get generic's class

前端 未结 3 1502
南方客
南方客 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:14

    It's not possible due to type erasure.

    There is the following workaround:

    class Model { 
    
        private T t; 
        private Class tag;
    
        public Model(Class tag) {
           this.tag = tag;
        }
    
        private void someMethod(){ 
           // use tag
        }  
    } 
    

提交回复
热议问题