How to access .class from a class using Generic?

When it comes to classes without generics, I can access this .class attribute as follows:

class Foo{ Class<Foo> getMyClass(){ return Foo.class; } } 

but how do I access this ".class" attribute if Foo has it in common? eg:

 class Foo<T>{ Class<Foo<T>> getMyClass(){ return (Foo<T>).class //this doesnt work... } } 

I tried to return Foo.class , but this will not work: "cannot cast from Class<Foo> to Class<Foo<T>>" .

How can I access the Foo<T> class?

+6
source share
2 answers

You can always do this:

 class Foo<T>{ Class<Foo<T>> getMyClass(){ return (Class<Foo<T>>)(Class<?>)Foo.class } } 

You will have thrown warnings removed because they are really unsafe - as others have already noted, the returned class object is no longer the " Foo<T> class" like the " Foo<SomethingElse> class".

+6
source

There is no way, due to the type of erasure . It:

 Foo<T>.class 

... cannot be obtained at run time, it will always be of the same type regardless of type T At runtime, this only exists:

 Foo.class 
+3
source

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


All Articles