Resolve generics in method parameters. - Java Reflection

Java examples for Reflection:Generic

Description

Resolve generics in method parameters.

Demo Code


//package com.java2s;
import java.lang.reflect.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class Main {
    /**/* w w  w  .  j  av  a2s  .  c  o m*/
     * 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) {
        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("[" + arrayType.getName());
                } else {
                    res = Class.forName("[L" + arrayType.getName() + ";");
                }
            } catch (ClassNotFoundException e) {
                throw new IllegalStateException(
                        "Failed to create array class", e);
            }
        }
        return res;
    }
}

Related Tutorials