Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a java.lang.Class with generics

I'm a C# guy learning Java and I'm trying to understand how generics work in Java.

Given a class or interface "SomeThing", I know I can do this to get the Class of that type:

Something.class

Now, given a generic interface

I'd love to write

(GenericInterface<SomeClass>).class 

but the compiler doesn't like that much.

Thanks for any help.

like image 712
jbenckert Avatar asked Dec 22 '22 07:12

jbenckert


1 Answers

That's because, thanks to erasure, there isn't a GenericInterface<SomeClass> class. There's just a GenericInterface class, which has a generic parameter.

If you want it so that you can call generically type-safe methods such as Class.cast() or Class.newInstance(), then you're out of luck. Generics are essentially a compile-time concept; there isn't enough information available at runtime to perform the generic checks, and so these methods can't be type-safe for an arbitrary Class instance.

The best you can do in this case is use the "raw" GenericInterface.class, then explicitly cast the results into GenericInterface<SomeClass> immediately afterwards. This will correctly give an "unchecked" warning, since as mentioned above there is no runtime check that the object really has the right generic parameter, and the JVM just has to take your word for it.

(Along the same lines, if you're trying to perform some sort of instanceof check, then that's simply not possible either. An object doesn't have a generic parameter to its class; only the variables you assign it to do. So again, these runtime checks just plain aren't possible due to the design constraints of the language.)

like image 129
Andrzej Doyle Avatar answered Jan 11 '23 02:01

Andrzej Doyle