Java Constructor getAnnotatedReceiverType()方法及示例
构造函数 类的 getAnnotatedReceiverType() 方法用于返回一个AnnotatedType对象,该对象代表AnnotatedType,用于指定该构造函数的接收者类型。如果构造函数有一个接收器参数,那么构造函数的接收器类型是可用的。如果这个构造函数没有接收方参数,或者有一个接收方参数,但没有对其类型进行注释,那么返回值是一个AnnotatedType对象,代表一个没有注释的元素。如果这个构造函数是一个顶级的静态成员,那么返回值是null。
语法
public AnnotatedType getAnnotatedReceiverType()
参数: 本方法不接受任何参数。
返回值: 该方法返回一个 AnnotatedType对象 ,代表这个Executable所代表的方法或构造函数的接收类型,如果这个Executable不能有一个接收参数,则返回null。
下面的程序说明了getAnnotatedReceiverType()方法:
程序1 :
// Java program to demonstrate// Constructor.getAnnotatedReceiverType() method import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;import java.lang.reflect.AnnotatedType;import java.lang.reflect.Constructor; public class GFG { public static void main(String[] args) throws NoSuchMethodException { // create a constructor class Constructor<?> c = Test.class.getConstructors()[0]; // apply getAnnotatedReceiverType() AnnotatedType atr = c.getAnnotatedReceiverType(); // print result System.out.println(atr); System.out.println("Type = " + atr.getType().getTypeName()); }}class Test { public Test(@Annotation Test test) {}} @Target({ ElementType.TYPE_USE })@Retention(RetentionPolicy.RUNTIME)@interface Annotation {}
输出。
sun.reflect.annotation.AnnotatedTypeFactory$AnnotatedTypeBaseImpl@12a3a380Type = Test
程序2
// Java program to demonstrate// Constructor.getAnnotatedReceiverType() method import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;import java.lang.reflect.AnnotatedType;import java.lang.reflect.Constructor; public class GFG { public static void main(String[] args) throws NoSuchMethodException { // create a constructor class Constructor<?> c = Demo.class.getConstructors()[0]; // apply getAnnotatedReceiverType() AnnotatedType atr = c.getAnnotatedReceiverType(); // print result System.out.println(atr); System.out.println("Type = " + atr.getType().getTypeName()); }}class Demo { public Demo(@PathVar String str) {}} @Target({ ElementType.TYPE_USE })@Retention(RetentionPolicy.RUNTIME)@interface PathVar {}输出。
sun.reflect.annotation.AnnotatedTypeFactory$AnnotatedTypeBaseImpl@12a3a380Type = Demo
参考文献: https://docs.oracle.com/javase/10/docs/api/java/lang/reflect/Constructor.html#getAnnotatedReceiverType()
