java - 如何将具有泛型的类型转换为java中的类?

标签 java generics reflection types spring-properties

我有一个方法对象。

我想用泛型提取返回 Type 并将其转换为 Class,以便将此类信息传递到 Spring PropertyResolver

Type type = myMethod.getGenericReturnType();
Class<?> returnType = /* ??? */;
environment.getProperty(key, returnType);

最佳答案

在实践中返回Type实例必须是以下之一:Class (例如 String ),GenericArrayType (例如 String[]T[]List<T>[] ),TypeVariable (例如 T )或 ParametrizedType (例如 List<String>List<T> )。另外Type也可以是WildcardType (例如 ? 中的 List<?> )但这些不能直接用作返回类型。

以下代码尝试根据这 5 个中的子接口(interface)给定实例来解析类。很少有 Type。不会扩展 5 中的任何一个,在这种情况下,我们只是说我们无法继续 UnsupportedOperationException .例如,您可以创建自己的合成 Type扩展类,但你为什么要这样做?

public static Class<?> type2Class(Type type) {
    if (type instanceof Class) {
       return (Class<?>) type;
    } else if (type instanceof GenericArrayType) {
       // having to create an array instance to get the class is kinda nasty 
       // but apparently this is a current limitation of java-reflection concerning array classes.
       return Array.newInstance(type2Class(((GenericArrayType)type).getGenericComponentType()), 0).getClass(); // E.g. T[] -> T -> Object.class if <T> or Number.class if <T extends Number & Comparable>
    } else if (type instanceof ParameterizedType) {
       return type2Class(((ParameterizedType) type).getRawType()); // Eg. List<T> would return List.class
    } else if (type instanceof TypeVariable) {
       Type[] bounds = ((TypeVariable<?>) type).getBounds();
       return bounds.length == 0 ? Object.class : type2Class(bounds[0]); // erasure is to the left-most bound.
    } else if (type instanceof WildcardType) {
       Type[] bounds = ((WildcardType) type).getUpperBounds();
       return bounds.length == 0 ? Object.class : type2Class(bounds[0]); // erasure is to the left-most upper bound.
    } else { 
       throw new UnsupportedOperationException("cannot handle type class: " + type.getClass());
    }
} 

请注意,代码未经测试,因此可能包含编译错误。我也不确定 GenericArrayType 是怎么回事会像 T[][] 这样的多维数组类型(也许它会返回 Object[] 而不是 Object[][] 如果 <T> 所以我们需要在这里做额外的工作)。如果需要任何更正,请告诉我。

最后,我们在这里尝试做的是在给定 Type 的情况下计算删除类我想知道是否有一些“标准”代码可以做到这一点,也许是 Sun/Oracle 编译器或代码分析器工具的一部分,您可以使用它们的实用程序并省去编码和维护它的麻烦……我没有通过快速浏览找到任何东西。

关于java - 如何将具有泛型的类型转换为java中的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48058645/

相关文章:

java - 当我将其转换为 pig 拉丁语时,如何正确阅读一行?

generics - 错误 : unable to infer enough type information about `_` ; type annotations or generic parameter binding required

java - 寻求java泛型方法的帮助

java - 获取通用类类型

java - 如何使用反射来获取对可以传递的 lambda 的引用?

reflection - 根据构建目标在编译时加载不同的程序集

java - 错误 : Unreachable code

java - OOP 中的覆盖、重载和隐藏

java - 重新架构应用程序以在多个服务器(JVM)上运行以提高性能

c# - 如何使用反射在静态类中查找私有(private)静态方法?