How to access the .class from a class with a Generic?

后端 未结 2 1430
Happy的楠姐
Happy的楠姐 2020-12-06 17:55

When it comes to classes without generics, i can access this .class attribute like this:

class Foo{
    Class getMyClass(){
        return Foo.cla         


        
相关标签:
2条回答
  • 2020-12-06 18:44

    You can always do this:

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

    You will have unchecked cast warnings, because it indeed is unsafe -- as others have mentioned, the returned class object is not any more "Foo<T>'s class" as "Foo<SomethingElse>'s class".

    0 讨论(0)
  • 2020-12-06 19:00

    There isn't a way, because of type erasure. This:

    Foo<T>.class
    

    ... can not be obtained at runtime, it will always be the same type no matter what's the type of T. At runtime only this exists:

    Foo.class
    
    0 讨论(0)
提交回复
热议问题