How to get a common class

Class Model<T>{

   private T t;

   .....


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

   .....

}

Of course, this throws NPE.

Class c = t.getClass();

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

+3
source share
3 answers

This is not possible due to type erasure.

The following workaround exists:

class Model<T> { 

    private T t; 
    private Class<T> tag;

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

    private void someMethod(){ 
       // use tag
    }  
} 
+7
source

You can do this with reflection:

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

Source: https://habr.com/ru/post/1731894/


All Articles