【问题标题】:Java reflection for generics泛型的 Java 反射
【发布时间】:2018-03-27 16:14:27
【问题描述】:

我正在使用 Java 反射来公开自定义 eclipse 工具中的方法。

我正在编写方法getReturnType,它接受java.lang.reflect.Method 作为输入并返回Class<?> 的对象

private static Class<?> getReturnType(Method method) {
    Type type = ((ParameterizedType)method.getGenericReturnType()).getRawType();
    return getClass(type);
}

此代码编译良好,但在运行时我将Type 转换为ParameterizedType 时出现以下异常。

java.lang.ClassCastException: java.lang.Class 不能转换为 java.lang.reflect.ParameterizedType

请提出建议。谢谢!

【问题讨论】:

  • 忘了提到 getClass(type) 为输入类型对象返回 Class>

标签: java generics reflection


【解决方案1】:

这不起作用,因为您不能假设getGenericReturnType 的结果总是ParameterizedType。如果返回类型不是通用的,有时它只是Class。请参阅此示例,了解如何使用 instanceof 实现您所需要的:

Type returnType = method.getGenericReturnType();

if (returnType instanceof Class<?>) {
    return (Class<?>)returnType;
} else if(returnType instanceof ParameterizedType) {
    return getClass(((ParameterizedType)returnType).getRawType());
}

请注意,getGenericReturnType 可能会返回更多可能的 Type 子接口,您需要以某种方式对其进行处理,方法是同时处理它们或引发运行时异常。

有关更多信息/示例,请参阅this article

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-25
    • 1970-01-01
    • 2020-09-02
    • 1970-01-01
    相关资源
    最近更新 更多