0

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

1
  • 4
    As a best-practice, I suggest you include the original exception 'e' as the source for the RuntimeException you throw. You will gain so much time having access to the original exception, the one that says what really went wrong. Good that you provide and additionnal message with the context though :-) Commented Sep 24, 2009 at 17:34

2 Answers 2

3

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.

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

Comments

0

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

The approach there is described in this article.

Comments

Your Answer

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