集册 Java实例教程 解决方法参数中的泛型。

解决方法参数中的泛型。

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

532
解决方法参数中的泛型。


//package com.nowjava;
/*
n o w j a   v  a . c o m - 时  代  Java 提 供
*/

import java.lang.reflect.*;

import java.util.ArrayList;

import java.util.List;

import java.util.Map;


public class Main {

    /**

     * Resolve generics in method parameters.

     *

     * @param method   method to resolve parameters

     * @param generics type generics

     * @return resolved method parameter types

     */

    public static List<Class<?>> getMethodParameters(final Method method,

            final Map<String, Type> generics) {

        final List<Class<?>> params = new ArrayList<Class<?>>();

        for (Type type : method.getGenericParameterTypes()) {

            params.add(resolveClass(type, generics));

        }

        return params;

    }


    /**

     * 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) {
            /** from 
            nowjava - 时  代  Java**/

        Class<?> res;

        if (type instanceof Class) {

            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(
展开阅读全文