Java 反射之 GenericDeclaration

java.lang.reflect.GenericDeclaration是Java反射包中,所有可以声明泛型类型的语法元素的父接口;

public interface GenericDeclaration extends AnnotatedElement {
    /**
     * Returns an array of {@code TypeVariable} objects that
     * represent the type variables declared by the generic
     * declaration represented by this {@code GenericDeclaration}
     * object, in declaration order.  Returns an array of length 0 if
     * the underlying generic declaration declares no type variables.
     *
     * @return an array of {@code TypeVariable} objects that represent
     *     the type variables declared by this generic declaration
     * @throws GenericSignatureFormatError if the generic
     *     signature of this generic declaration does not conform to
     *     the format specified in
     *     The Java™ Virtual Machine Specification
     */
    public TypeVariable[] getTypeParameters();
}

如上所示,只有一个方法,获取此语法元素上声明的泛型变量;
GenericDeclaration有三个子类,java.lang.Class,java.lang.reflect.Constructor和java.lang.reflect.Method,也就是说,在Java中,只有在类,类的构造方法和类的方法这三个语法元素上可以声明泛型变量;

public class GenericDeclarationSample {

	public   GenericDeclarationSample(T3 t3, T4 t4) {
	}
	
	public  T6 test(T5 t5){
		return null;
	}
}

通过如下的方式,可以反射获取到这三个地方的声明的泛型变量;

public static void main(String[] args) throws NoSuchMethodException, SecurityException {
		TypeVariable>[] classTypeParameters = GenericDeclarationSample.class.getTypeParameters();
		
		Constructor contructor = GenericDeclarationSample.class.getConstructor(Object.class,Object.class);
		TypeVariable>[] contructorTypeParameters = contructor.getTypeParameters();
		
		Method method = GenericDeclarationSample.class.getMethod("test", Object.class);
		TypeVariable[] methodTypeParameters = method.getTypeParameters();
	}

你可能感兴趣的:(Java)