集册 Java实例教程 调用此方法可正确解析根查找程序或继承的查找程序方法的返回类型。

调用此方法可正确解析根查找程序或继承的查找程序方法的返回类型。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

507
调用此方法可正确解析根查找程序或继承的查找程序方法的返回类型。
/*NowJava.com 提 供*/

//package com.nowjava;

import java.lang.reflect.*;


import java.util.Map;


public class Main {

    /**

     * Called to properly resolve return type of root finder or inherited finder method.

     * Supposed to return enough type info to detect return type (collection, array or plain object).

     *

     * @param method   method to analyze

     * @param generics generics resolution map for method class (will be null for root)

     * @return return type class

     */

    public static Class<?> getReturnClass(final Method method,

            final Map<String, Type> generics) {

        final Type returnType = method.getGenericReturnType();

        return resolveClass(returnType, generics);

    }


    /**

     * Resolves top class for provided type (for example, for generified classes like {@code List<T>} it

     * returns base type List).

     *

     * @param type     type to resolve

     * @param generics root class generics mapping

     * @return resolved class

     */

    public static Class<?> resolveClass(final Type type,

            final Map<String, Type> generics) {

        Class<?> res;

        if (type instanceof Class) {
        /*
        来 自*
         NowJava.com - 时  代  Java
        */

            res = (Class) type;

        } else if (type instanceof ParameterizedType) {

            res = resolveClass(((ParameterizedType) type).getRawType(),

                    generics);

        } else if (type instanceof TypeVariable) {

            res = resolveClass(

                    generics.get(((TypeVariable) type).getName()), generics);

        } else if (type instanceof WildcardType) {

            final Type[] upperBounds = ((WildcardType) type)

                    .getUpperBounds();

            res = resolveClass(upperBounds[0], generics);

        } else {

            final Class arrayType = resolveClass(

                    ((GenericArrayType) type).getGenericComponentType(),

                    generics);

            try {

                // returning complete array class with resolved type

                if (arrayType.isArray()) {

                    res = Class.forName(
展开阅读全文