简体   繁体   English

Java使用泛型创建新类

[英]Java Creating a new Class with Generics

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>. 例如,如果所讨论的方法原型是List <Book> getBooks(),则上面的代码将只返回一个List而不是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. 我可以很容易地获得Generic类型,但是一旦获得它,我便不知道该如何处理。

Thanks in advance 提前致谢

To get the generic return type of a method, use the getGenericReturnType() method. 要获取方法的通用返回类型,请使用getGenericReturnType()方法。 This returns a Type, which you then test and down cast to a ParameterizedType which you can then query for the type parameters. 这将返回一个Type,然后您可以对其进行测试并将其转换为ParameterizedType ,然后可以查询该TypeParameter。

Not everything is possible via reflection, but is with a bytecode-library like ObjectWeb ASM . 并不是所有的事情都可以通过反射实现,但是通过像ObjectWeb ASM这样的字节码库可以实现。

The approach there is described in this article . 本文介绍了该方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM