簡體   English   中英

如何獲取使用反射為其創建收集對象的類類型

[英]How to get the class type for which a collection object is created using 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的類對象,但沒有得到如何做。 上面的代碼是靜態的,我在上面的情況下知道,但這必須是動態完成的,並且上面只是一個演示代碼,該程序將實時獲取必須將其方法作為參數訪問的類。

您可以使用getGenericReturnType

Type t = method.getGenericReturnType();

如果打印t ,則會發現它是一個java.lang.reflect.ParameterizedType Set<Employee>

但是,您現在已經踏入懸崖,進入了怪異的java.lang.reflect.Type及其子類型的世界。 如果要正確發現t是其他類型的子類型還是超類型(例如HashSet<E> ,則需要至少部分實現此處描述的算法

要簡單地獲取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()返回聲明中的類型。 如果要從Foo<String>的類中獲取List<String> ,則需要執行類似new Foo<String>() {}以便將type參數保存在類文件中,然后做一些魔術,讓你替換類型變量的情況下T與類型參數T 這開始引起一些真正的沉重負擔。


編輯了一個有關如何測試參數化類型的簡單可分配性的示例。

這將處理類似Set<Employee>HashSet<Employee> ,以及類似示例中描述的更為復雜的情況的情況,使用Foo<F> implements Set<F>Bar<A, B> extends Foo<B> 這不能處理諸如List<List<T>>類的嵌套類型或帶有通配符的類型。 這些更加復雜。

基本上,您會找到通用超類型,例如Set<E> ,然后將每個類型變量(對於Set只是E )替換為與其正確對應的type參數。

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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM