I have a function that expects class
someMethod(Class<T> c){}
which for a normal class it's easy, you can just do
someMethod(MyObject.class)
But for some reason this wont work
someMethod(MyObject<User>.class)
wont compile. Why?
There's no such thing. MyObject<User>.class
would be exactly the same thing as MyObject.class
. There is no separate Class
object for different subtypes; Class
is an API that only represents a "raw" type, not generic. It's just not what Class
is for.
If you need one to make generics work, just cast it: e.g. (Class<MyObject<User>>) MyObject.class
.
In simple words, it's your object which decided what would be the type of the object as you already declared that when object was created. There is not point in doing object<Type>.class
as it's already determined during object creation. You can always typecast if required.