Reputation: 964
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.
Upvotes: 5
Views: 4460
Reputation: 4374
Generics are fundamentally different in Java and C#, because in Java generics are checked at compile-time but then changed to the concrete class in a process known as type erasure. Using your example, GenericInterface<SomeClass>
becomes GenericInterface
at runtime.
It's a slightly half-assed implementation of generics, and as you're seeing it does present some problems (which you can usually work around). It was done that way to maintain backwards-compatibility with older versions of Java.
Upvotes: 2
Reputation: 298898
No, Java Generics don't work that way.
You can do GenericInterface.class
to get at the non-generic root class, but there is no separate class for the generic version.
Upvotes: 0
Reputation: 103797
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.)
Upvotes: 9