Java使用泛型创建一个新类

时间:2009-09-24 17:16:47

标签: java generics reflection

我遇到了一个问题,我的程序给定了一个对象和一个属性名称,我想返回方法的返回类型。

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());
     }
}

除非方法的返回类型具有通用定义,否则此解决方案很有效。例如,如果所讨论的方法原型是List&lt; Book&gt; getBooks(),上面的代码只会返回一个List而不是List&lt; Book&gt;。我有什么方法可以做到这一点吗?我可以很容易地获得Generic类型,一旦我拥有它,我就不知道如何处理它。

提前致谢

2 个答案:

答案 0 :(得分:3)

要获取方法的泛型返回类型,请使用getGenericReturnType()方法。这将返回一个Type,然后您可以测试并向下转换为ParameterizedType,然后您可以查询类型参数。

答案 1 :(得分:0)

并非一切都可以通过反射实现,而是使用像ObjectWeb ASM这样的字节码库。

this article中描述了这种方法。