views:

238

answers:

6

Is it possible to get the type of a generic parameter?

An example:

public final class voodoo {
    public static chill(List<?> aListWithTypeSpiderMan) { 
        // Here I'd like to get the Class-Object 'SpiderMan'
        Class typeOfTheList = ???;
    }

    public static void main(String... args) {
        chill(new List<SpiderMan>());
    }
}

~Chris

+2  A: 

This is impossible because generics in Java are only considered at compile time. Thus, the Java generics are just some kind of pre-processor. However you can get the actual class of the members of the list.

bertolami
Yeah that is what I am doing now. But now I want to know the type even if the list is empty. But four guys can't be wrong. Thank you (all)!
cimnine
+1  A: 

No it isn't possible.

You can get a generic type of a field given a class is the only exception to that rule and even that's a bit of a hack.

See Knowing type of generic in Java for an example of that.

cletus
+1  A: 

No, because they're erased on runtime.

True Soft
+3  A: 

Nope, that is not possible. Due to downwards compatibility issues, Java's generics are based on type erasure, i.a. at runtime, all you have is a non-generic List object. There is some information about type parameters at runtime, but it resides in class definitions (i.e. you can ask "what generic type does this field's definition use?"), not in object instances.

Michael Borgwardt
Though java could store this as meta data during runtime, couldn't it? I hoped it would. Bad Luck.
cimnine
A: 

One construct, I once stumbled upon looked like

Class<T> persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];

So there seems to be some reflection-magic around that I unfortunetly don't fully understand... Sorry.

Regards

Mike [;-)

DerMike
A: 

Because of type erasure the only way to know the type of the list would be to pass in the type as a parameter to the method:

public class Main {

    public static void main(String[] args) {
        doStuff(new LinkedList<String>(), String.class);

    }

    public static <E> void doStuff(List<E> list, Class<E> clazz) {

    }

}
Jared Russell