views:

113

answers:

2

I'm running into a problem with my program where given an object and an attribute name I want to return the method's return type.

public static Class<?> getAttributeType(Object object, String attributeName) {
     try {
         Method method = object.getClass().getMethod(
             "get" + StringUtils.capitalize(attributeName));
         return method.getReturnType();
     } catch (Exception e) {
          throw new RuntimeException("Unable to find the attribute:"
              + attributeName + " in class: "
              + object.getClass().getName());
     }
}

This solution works great unless the return type of a method has a generic defined. For example if method prototype in question is List<Book> getBooks(), the code above would just return a List instead of a List<Book>. Is there any way for me to accomplish this? I can get the Generic type easily, I just don't know what to do with it once I have it.

Thanks in advance

+3  A: 

To get the generic return type of a method, use the getGenericReturnType() method. This returns a Type, which you then test and down cast to a ParameterizedType which you can then query for the type parameters.

Pete Kirkham
A: 

Not everything is possible via reflection, but is with a bytecode-library like ObjectWeb ASM.

The approach there is described in this article.

pmf