繁体   English   中英

如何从Java方法获取返回的Objects对象类型列表?

[英]How to get a returned List of Objects object type from a Java method?

我在Class中有一个getter方法,该方法返回对象列表。 看起来像这样:

public List <cars> getCars() {

// some code here

}

该类还包含其他一些吸气剂。 在另一个类中,我想获取第一个类中包含的所有getter方法,并显示这些方法的名称和返回的数据类型。

我能够获得上述方法的名称(getCars),并且它返回了数据类型(List)。 但是,我似乎无法获得“汽车”作为列表包含的对象的类型。 我能得到的最好的是“ ObjectType”。 有没有一种方法可以显示“汽车”? 我已经阅读了有关类型擦除的信息,以及如何在字节码中删除泛型的内容,因为它仅用于Java编译器。 我的问题与类型擦除有关吗?

是否可以显示“汽车”一词? 当我读到Type Erasure时,似乎有一种从列表中获取泛型的方法,但是我看到的示例是针对String和Integer的,而不是针对对象的。

获取java.util.List的通用类型

谢谢

您可以使用标准Java反射掌握方法的(一般)信息:

Class<?> yourClass = Class.forName("a.b.c.ClassThatHasTheMethod");
Method getCarsMethod = yourClass.getMethod("getCars");
Type returnType = getCarsMethod.getGenericReturnType();

现在,没有一种特别优雅的方法来处理这个returnType变量(我知道)。 它可以是普通的Class ,也可以是任何子接口 (例如ParameterizedType )。 在过去,当我这样做时,我只需要使用instanceof和cast来处理案例。 例如:

if (returnType instanceof Class<?>) {
    Class<?> returnClass = (Class<?>)returnType;
    // do something with the class
}
else if (returnType instanceof ParameterizedType) {
    // This will be the case in your example
    ParameterizedType pt = (ParameterizedType)returnType;
    Type rawType = pt.getRawType();
    Type[] genericArgs = pt.getActualTypeArguments();

    // Here `rawType` is the class "java.util.List",
    // and `genericArgs` is a one element array containing the
    // class "cars".  So overall, pt is equivalent to List<cars>
    // as you'd expect.
    // But in order to work that out, you need
    // to call something like this method recursively, to
    // convert from `Type` to `Class`...
}
else if (...) // handle WildcardType, GenericArrayType, TypeVariable for completeness

暂无
暂无

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

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