代码之家  ›  专栏  ›  技术社区  ›  Glains

获取具有反射的特定参数化类型

  •  0
  • Glains  · 技术社区  · 6 年前

    我知道我可以通过以下方式获得类的参数化类型:

    Type[] genericInterfaces = getClass().getGenericInterfaces();
    for (Type genericInterface : genericInterfaces) {
        if (genericInterface instanceof ParameterizedType) {
            ParameterizedType type = (ParameterizedType) genericInterface;
            // do something 
        }
    }
    

    但是假设我需要检查特定的参数化类型,比如 List<T> . 这个 type 提供 getRawType().getTypeName() 我可以把它与 List . 走这条路对吗?

    更新:

    更具体一点:如何让所有bean实现一个特定的接口,然后将映射上的泛型类型参数注册为键,将bean注册为值。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Dean Xu    6 年前

    List<T>

    GenericUtil

    // your approach only works for this situation
    class Foo implements List<String>{}
    // your approach not work in these situations
    class A<T> implements List<T>{}
    class B extends A<Integer>{}
    class C extends A<A<C>>{}
    
    GenericUtil.getGenericTypes(Foo.class, List.class); // {String}
    GenericUtil.getGenericTypes(A.class, List.class); // {T}
    GenericUtil.getGenericTypes(B.class, List.class); // {Integer.class}
    GenericUtil.getGenericTypes(C.class, List.class); // {A<C>}