get Method Generic Parameter Types - Java Reflection

Java examples for Reflection:Generic

Description

get Method Generic Parameter Types

Demo Code


//package com.java2s;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class Main {
    public static Class<?> getMethodGenericParameterTypes(Method method,
            int paramIndex) {
        Class<?> literalType = method.getParameterTypes()[paramIndex];
        Type genericType = method.getGenericParameterTypes()[paramIndex];
        return chooseOneType(literalType, genericType);

    }//ww  w.  jav a  2s. c om

    static Class<?> chooseOneType(Class<?> literalType, Type genericType) {
        if (genericType instanceof ParameterizedType) {
            return digFromGenericType(genericType);
        }
        return literalType;
    }

    static Class<?> digFromGenericType(Type genericType) {
        Type[] typeArguments = ((ParameterizedType) genericType)
                .getActualTypeArguments();
        Type type = typeArguments[0];
        if (type instanceof ParameterizedType) {
            return digFromGenericType(type);
        } else {
            return (Class<?>) type;
        }

    }
}

Related Tutorials