Saturday, 21 July 2012

The real way to get information about Java Generics

An other bit of plagarism I am afraid but again on a task that I had searche for long and hard.
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

Which is correct!

The article what gets the credit for this is here: Java Reflection: Generics by Jakob Jenkov.

No comments:

Post a Comment