0
点赞
收藏
分享

微信扫一扫

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();
}

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

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();
}


举报

相关推荐

0 条评论