如何获取使用反射创建集合对象的类类型

时间:2017-05-30 17:39:56

标签: java reflection

我需要你的帮助来解决这个问题,我一直试图找到答案,但没有找到答案,而且我没有多少时间来完成任务。

以下代码:

 public class MainClass {
      @SuppressWarnings("unchecked")
      public static void main(String args[]) throws ClassNotFoundException {
           @SuppressWarnings("rawtypes")
           Class aClass = EmployeeDao.class;
           Method[] methods = aClass.getDeclaredMethods();

           @SuppressWarnings("rawtypes")
           Class returnType = null;
           for (Method method : methods) {
               if (!method.getReturnType().equals(Void.TYPE)) {
                  System.out.println(method.getName());

                  returnType = method.getReturnType();
                  if (returnType.isAssignableFrom(HashSet.class)) {
                      System.out.println("hash set");
                  }  
               }
           }
     }
 }

在上面的代码中我得到了一个类的所有方法并检查它的返回类型是否为HashSet,在这种情况下我需要找出set对象包含的对象类型,例如EmployeeDao的下面方法类:

public Set<Employee> findAllEmployees() {
     //some code here
}

我想为上面的方法获取Employee的类对象,我没有得到如何做到这一点。上面的代码是静态的,我知道在上面的例子中,但这必须动态完成,上面只是一个演示代码,实时这个程序将得到其方法必须作为参数访问的类。

1 个答案:

答案 0 :(得分:2)

在您的情况下,您可以使用getGenericReturnType

Type t = method.getGenericReturnType();

如果您打印t,您会发现它是java.lang.reflect.ParameterizedType Set<Employee>

然而,你现在已经走出了悬崖,进入了java.lang.reflect.Type及其亚型的古怪世界。如果您想要正确发现t是否是某种其他类型的子类型或超类型,例如HashSet<E>,则需要至少部分实施the algorithm described here

要简单地获得Employee课程,您可以执行以下操作:

if (t instanceof ParameterizedType) {
    Type[] args = ((ParameterizedType) t).getActualTypeArguments();
    for (Type arg : args) {
        // This will print e.g. 'class com.example.Employee'
        System.out.println(arg);
    }
}

但是,作为对此的一般说明,如果你有这样的情况:

class Foo<T> {
    List<T> getList() {return ...;}
}

然后你这样做:

Foo<String>  f = new Foo<String>();
Method getList = f.getClass().getDeclaredMethod("getList");
Type   tReturn = getList.getGenericReturnType();
// This prints 'List<T>', not 'List<String>':
System.out.println(tReturn);

泛型返回类型为List<T>,因为getGenericReturnType()返回声明中的类型。如果你想要,例如从List<String>的类中获取Foo<String>,您需要执行new Foo<String>() {}之类的操作,以便将类型参数保存在类文件中,然后执行一些魔术使用T的type参数替换类型变量T的实例。这开始进入一些非常重要的反思。

编辑了一个如何测试参数化类型的简单可分配性的例子。

这会处理Set<Employee>HashSet<Employee>之类的内容,以及示例中描述的更为复杂的案例,Foo<F> implements Set<F>Bar<A, B> extends Foo<B>。这不会处理嵌套类型(如List<List<T>>)或带有通配符的类型。那些更复杂。

基本上,您可以找到通用超类型,例如Set<E>,然后使用与其正确对应的type参数替换每个类型变量(仅E Set)。

package mcve;

import java.util.*;
import java.lang.reflect.*;

class TypeTest {
    class Employee {}
    abstract class Foo<F>    implements Set<F> {}
    abstract class Bar<A, B> extends    Foo<B> {}
    Set<Employee> getSet() { return Collections.emptySet(); }

    public static void main(String[] args) throws ReflectiveOperationException {
        Method m = TypeTest.class.getDeclaredMethod("getSet");
        Type   r = m.getGenericReturnType();
        if (r instanceof ParameterizedType) {
            boolean isAssignable;
            isAssignable =
            //  Testing i.e. Set<Employee> assignable from HashSet<Employee>
                isNaivelyAssignable((ParameterizedType) r,
                                    HashSet.class,
                                    Employee.class);
            System.out.println(isAssignable);
            isAssignable =
            //  Testing i.e. Set<Employee> assignable from Bar<String, Employee>
                isNaivelyAssignable((ParameterizedType) r,
                                    Bar.class,
                                    String.class,
                                    Employee.class);
            System.out.println(isAssignable);
        }
    }

    static boolean isNaivelyAssignable(ParameterizedType sType,
                                       Class<?>          tRawType,
                                       Class<?>...       tArgs) {
        Class<?> sRawType = (Class<?>) sType.getRawType();
        Type[]   sArgs    = sType.getActualTypeArguments();
        // Take the easy way out, if possible.
        if (!sRawType.isAssignableFrom(tRawType)) {
            return false;
        }
        // Take the easy way out, if possible.
        if (sRawType.equals(tRawType)) {
            return Arrays.equals(sArgs, tArgs);
        }

        Deque<ParameterizedType> tHierarchyToS = new ArrayDeque<>();
        // Find the generic superclass of T whose raw type is the
        // same as S. For example, suppose we have the following
        // hierarchy and method:
        //  abstract class Foo<F>    implements Set<F> {}
        //  abstract class Bar<A, B> extends    Foo<B> {}
        //  class TypeTest { Set<Employee> getSet() {...} }
        // The we invoke isNaivelyAssignable as follows:
        //  Method m = TypeTest.class.getDeclaredMethod("getSet");
        //  Type   r = m.getGenericReturnType();
        //  if (t instanceof ParameterizedType) {
        //      boolean isAssignable =
        //          isNaivelyAssignable((ParameterizedType) r,
        //                              Bar.class,
        //                              String.class,
        //                              Employee.class);
        //  }
        // Clearly the method ought to return true because a
        // Bar<String, Employee> is a Set<Employee>.
        // To get there, first find the superclass of T
        // (T is Bar<String, Employee>) whose raw type is the
        // same as the raw type of S (S is Set<Employee>).
        // So we want to find Set<F> from the implements clause
        // in Foo.
        Type tParameterizedS = findGenericSuper(sRawType, tRawType, tHierarchyToS);
        if (tParameterizedS == null) {
            // Somebody inherited from a raw type or something.
            return false;
        }
        // Once we have Set<F>, we want to get the actual type
        // arguments to Set<F>, which is just F in this case.
        Type[] tArgsToSuper = tHierarchyToS.pop().getActualTypeArguments();
        if (tArgsToSuper.length != sArgs.length) {
            return false; // or throw IllegalArgumentException
        }
        // Then for each type argument to e.g. Set in the generic
        // superclass of T, we want to map that type argument to
        // one of tArgs. In the previous example, Set<F> should map
        // to Set<Employee> because Employee.class is what we passed
        // as the virtual type argument B in Bar<A, B> and B is what
        // is eventually provided as a type argument to Set.
        for (int i = 0; i < tArgsToSuper.length; ++i) {
            // tArgToSuper_i is the type variable F
            Type tArgToSuper_i = tArgsToSuper[i];

            if (tArgToSuper_i instanceof TypeVariable<?>) {
                // Copy the stack.
                Deque<ParameterizedType> tSupers = new ArrayDeque<>(tHierarchyToS);
                do {
                    TypeVariable<?> tVar_i = (TypeVariable<?>) tArgToSuper_i;
                    // The type variable F was declared on Foo so vDecl is
                    // Foo.class.
                    GenericDeclaration vDecl = tVar_i.getGenericDeclaration();
                    // Find the index of the type variable on its declaration,
                    // because we will use that index to look at the actual
                    // type arguments provided in the hierarchy. For example,
                    // the type argument F in Set<F> is at index 0 in Foo<F>.
                    // The type argument B to Foo<B> is at index 1 in Bar<A, B>.
                    TypeVariable<?>[] declVars = vDecl.getTypeParameters();
                    int tVarIndex = Arrays.asList(declVars).indexOf(tVar_i);
                    // Eventually we will walk backwards until we actually hit
                    // the class we passed in to the method, Bar.class, and are
                    // able to map the type variable on to one of the type
                    // arguments we passed in.
                    if (vDecl.equals(tRawType)) {
                        tArgToSuper_i = tArgs[tVarIndex];
                    } else {
                        // Otherwise we have to start backtracking through
                        // the stack until we hit the class where this type
                        // variable is declared. (It should just be the first
                        // pop(), but it could be the type variable is declared
                        // on e.g. a method or something, in which case we
                        // will empty the stack looking for it and eventually
                        // break from the loop and return false.)
                        while (!tSupers.isEmpty()) {
                            ParameterizedType tSuper    = tSupers.pop();
                            Class<?>          tRawSuper = (Class<?>) tSuper.getRawType();
                            if (vDecl.equals(tRawSuper)) {
                                tArgToSuper_i = tSuper.getActualTypeArguments()[tVarIndex];
                                break;
                            }
                        }
                    }
                } while (tArgToSuper_i instanceof TypeVariable<?>);
            }

            if (!tArgToSuper_i.equals(sArgs[i])) {
                return false;
            }
        }

        return true;
    }

    // If we have a raw type S which is Set from e.g. the parameterized
    // type Set<Employee> and a raw type T which is HashSet from e.g.
    // the parameterized type HashSet<Employee> we want to find the
    // generic superclass of HashSet which is the same as S, pushing
    // each class in between on to the stack for later. Basically
    // just walk upwards pushing each superclass until we hit Set.
    // For e.g. s = Set.class and t = HashSet.class, then:
    //  tHierarchyToS = [Set<E>, AbstractSet<E>].
    // For e.g. s = Set.class and t = Bar.class, then:
    //  tHierarchyToS = [Set<F>, Foo<B>]
    static ParameterizedType findGenericSuper(Class<?> s,
                                              Class<?> t,
                                              Deque<ParameterizedType> tHierarchyToS) {
        ParameterizedType tGenericSuper = null;

        do {
            List<Type> directSupertypes = new ArrayList<>();
            directSupertypes.add(t.getGenericSuperclass());
            Collections.addAll(directSupertypes, t.getGenericInterfaces());

            for (Type directSuper : directSupertypes) {
                if (directSuper instanceof ParameterizedType) {
                    ParameterizedType pDirectSuper = (ParameterizedType) directSuper;
                    Class<?>          pRawSuper    = (Class<?>) pDirectSuper.getRawType();

                    if (s.isAssignableFrom(pRawSuper)) {
                        tGenericSuper = pDirectSuper;
                        t             = pRawSuper;
                        tHierarchyToS.push(tGenericSuper);
                        break;
                    }
                }
            }
        } while (!s.equals(t) && tGenericSuper != null);

        return tGenericSuper;
    }
}