天天看点

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
     *     <cite>The Java™ Virtual Machine Specification</cite>
     */
    public TypeVariable<?>[] getTypeParameters();
}      
public class GenericDeclarationSample<T1,T2> {

  public  <T3,T4> GenericDeclarationSample(T3 t3, T4 t4) {
  }
  
  public <T5,T6> T6 test(T5 t5){
    return null;
  }
}      
public static void main(String[] args) throws NoSuchMethodException, SecurityException {
    TypeVariable<Class<GenericDeclarationSample>>[] classTypeParameters = GenericDeclarationSample.class.getTypeParameters();
    
    Constructor<GenericDeclarationSample> contructor = GenericDeclarationSample.class.getConstructor(Object.class,Object.class);
    TypeVariable<Constructor<GenericDeclarationSample>>[] contructorTypeParameters = contructor.getTypeParameters();
    
    Method method = GenericDeclarationSample.class.getMethod("test", Object.class);
    TypeVariable<Method>[] methodTypeParameters = method.getTypeParameters();
  }