Get type of a generic parameter in java with reflection?

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.

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 Dec 14 '09 at 14:25.

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.

I hoped it would. Bad Luck. – cimnine Dec 14 '09 at 14:27 You're wrong.

See Andrey Rodionov's solution. – Aslak Hellesøy Aug 31 at 11:39 @user99475: Nope. I am right and Andrey is wrong.

He is referring to the type information I mention in the second part of my answer, but that is not what the question asks for. – Michael Borgwardt Aug 31 at 12:05.

Actually I got this to work. Consider the following snippet: Method m; Type genericParameterTypes = m. GetGenericParameterTypes(); for (int I = 0; I value)" } } I'm using jdk 1.6.

1 -1: this does not solve the problem in the question; it only gives you the type declared in the method signature, not the actual runtime type. – Michael Borgwardt Aug 31 at 12:03.

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.

One construct, I once stumbled upon looked like Class persistentClass = (Class) ((ParameterizedType) getClass(). GetGenericSuperclass()). GetActualTypeArguments()0; So there seems to be some reflection-magic around that I unfortunetly don't fully understand... Sorry.

Regards Mike ;-).

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. Class); } public static void doStuff(List list, Class clazz) { } }.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions