Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Acquiring generic class type

Tags:

java

generics

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

like image 545
malejpavouk Avatar asked Feb 13 '11 12:02

malejpavouk


2 Answers

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.

like image 121
Sergei Tachenov Avatar answered Oct 16 '22 23:10

Sergei Tachenov


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.

like image 38
irreputable Avatar answered Oct 16 '22 22:10

irreputable