Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 333
Max Avatar asked Jun 20 '26 12:06

Max


1 Answers

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
    }  
} 
like image 179
axtavt Avatar answered Jun 23 '26 00:06

axtavt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!