This is related to the problem of using Java reflection to examine generics. There are may articles that will tell you is just can't be done at runtime and that the information has disappeared.
Not so!
The following code will show that you can do it:
class TargetClass
{
public List<String> getData() { return null; }
}
Method method = TargetClass.class.getMethod("getData", null);
Type returnType = method.getGenericReturnType();
if(returnType instanceof ParameterizedType){
ParameterizedType type = (ParameterizedType) returnType;
Type rawType = type.getRawType() ;
Class rawTypeClass = (Class) rawType ;
Type[] typeArguments = type.getActualTypeArguments();
System.out.println("returnType = " + rawTypeClass );
if ( List.class.isAssignableFrom(rawTypeClass) ) System.out.println("Is a list");
for(Type typeArgument : typeArguments){
Class typeArgClass = (Class) typeArgument;
System.out.println("typeArgClass = " + typeArgClass);
}
this prints out:
returnType = interface java.util.List
Is a list
typeArgClass = class java.lang.String
Is a list
typeArgClass = class java.lang.String
Which is correct!
The article what gets the credit for this is here: Java Reflection: Generics by
No comments:
Post a Comment