Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

generics

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

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

but how do i access this ".class" attribute if Foo has a generic? like this:

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

i have tried to return Foo.class, but this is not going to work: "cannot cast from Class<Foo> to Class<Foo<T>>".

How can i access Foo<T>'s class?

like image 870
pr00thmatic Avatar asked Jul 13 '13 22:07

pr00thmatic


2 Answers

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".

like image 102
newacct Avatar answered Oct 20 '22 02:10

newacct


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
like image 39
Óscar López Avatar answered Oct 20 '22 04:10

Óscar López