Hi is there any way in Java to get staticly generic class type
I have ended up with construct
List<TaskLocalConstraints> l = new ArrayList<TaskLocalConstraints>();
Class<List<TaskLocalConstraints>> c = (Class<List<TaskLocalConstraints>>)l.getClass();
I am wondering, if there exists something like:
Class c = List<TaskLocalConstraints>.class;
(I really dont want to construct new Object just to get its type)
Thanks
Since all List<something>
classes actually correspond to the same class at runtime, you could do this:
Class<List<TaskLocalConstraints>> c
= (Class<List<TaskLocalConstraints>>) List.class;
But for some reason, Java doesn't like it. Tried it with String:
Laj.java:9: inconvertible types
found : java.lang.Class<java.util.List>
required: java.lang.Class<java.util.List<java.lang.String>>
Class<List<String>> c = (Class<List<String>>) List.class;
Well, let's fool it then:
Class<List<String>> c =
(Class<List<String>>) (Class<?>) List.class;
It's silly, but it works. It produces an "unchecked" warning, but so does your example. Note that it doesn't result in the same class as your example, though. Your example returns the actual class of the object, namely ArrayList
. This one returns List
, obviously.
Basically, just cast around to fool the compiler. At runtime it's a simple Class
anyway.
a utility method:
public static <C extends Collection, E, T extends Collection<E>>
Class<T> cast(Class<C> classC, Class<E> classE)
{
return (Class<T>)classC;
}
Class<List<TaskLocalConstraints>> c =
cast(List.class, TaskLocalConstraints.class);
If you need a real Type
complete with runtime generic type info, that's a different story.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With