1

Every questions about the java reflection on generic types I found, were asking about getting parameters of a generic type. In my case, I have a ParameterizedType and want to get the Generic container class.

For example, suppose a

ParameterizedTypeImpl.toString()

returns

java.util.List<test.Bar>

Now I want to get a Class of java.util.List.

It might sound a little wired for you, but I need you to suppose it is what it is!

So what I need is something like

 Class cls = ((MagicCast)ParameterizedTypeImpl.mayBeAMagicHere()).someOtherMagic();
 //Now cls is of type List

The only way I can think of is to use subString or regex to get java.util.List out of the ParameterizedTypeImpl.toString() and then use class.forName to get the class. But I don't know how portable it is. Is it possible some versions of java have other implementation for the toString of a ParameterizedTypeImpl?

Is there any better solution than that?

Thank you.

1 Answer 1

3

getRawType should do the trick?

Class<?> theClass = (Class<?>) yourParameterizedType.getRawType();

The cast should be safe since the docs say that the returned value is the Type object representing the class or interface that declared this type, but well, no guarantees guaranteed :)

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you man, Now I see I was working with a Type casted version of a ParameterizedType and did not see that little getRawType. "guarantees guaranteed" hell yeah :) So true. But tell this to those fat ass employers and see what happens ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.