Get type of a generic parameter in Java with reflection

后端 未结 18 2218
死守一世寂寞
死守一世寂寞 2020-11-22 05:56

Is it possible to get the type of a generic parameter?

An example:

public final class Voodoo {
    public static void chill(List aListWithTy         


        
18条回答
  •  不知归路
    2020-11-22 06:11

    I've coded this for methods which expect to accept or return Iterable. Here is the code:

    /**
     * Assuming the given method returns or takes an Iterable, this determines the type T.
     * T may or may not extend WindupVertexFrame.
     */
    private static Class typeOfIterable(Method method, boolean setter)
    {
        Type type;
        if (setter) {
            Type[] types = method.getGenericParameterTypes();
            // The first parameter to the method expected to be Iterable<...> .
            if (types.length == 0)
                throw new IllegalArgumentException("Given method has 0 params: " + method);
            type = types[0];
        }
        else {
            type = method.getGenericReturnType();
        }
    
        // Now get the parametrized type of the generic.
        if (!(type instanceof ParameterizedType))
            throw new IllegalArgumentException("Given method's 1st param type is not parametrized generic: " + method);
        ParameterizedType pType = (ParameterizedType) type;
        final Type[] actualArgs = pType.getActualTypeArguments();
        if (actualArgs.length == 0)
            throw new IllegalArgumentException("Given method's 1st param type is not parametrized generic: " + method);
    
        Type t = actualArgs[0];
        if (t instanceof Class)
            return (Class) t;
    
        if (t instanceof TypeVariable){
            TypeVariable tv =  (TypeVariable) actualArgs[0];
            AnnotatedType[] annotatedBounds = tv.getAnnotatedBounds();///
            GenericDeclaration genericDeclaration = tv.getGenericDeclaration();///
            return (Class) tv.getAnnotatedBounds()[0].getType();
        }
    
        throw new IllegalArgumentException("Unknown kind of type: " + t.getTypeName());
    }
    

提交回复
热议问题