Java Constructor getAnnotation()方法及示例
构造函数 类的 getAnnotation() 方法用于获取该构造函数对象对指定类型的注释,如果存在这样的注释,则为空。指定的类型被作为参数传递。
语法
public <T extends Annotation> T getAnnotation(Class<T> annotationClass)
参数: 该方法接受一个参数annotationClass,代表与注释类型对应的Class对象。
返回值: 如果该元素上存在指定的注释类型,该方法返回 该元素的注释 ,否则为空。
异常: 如果给定的注释类是空的,这个方法会抛出NullPointerException。
下面的程序说明了getAnnotation()方法:
程序1 :
// Java program to demonstrate// Constructor.getAnnotation() method import java.lang.annotation.Annotation;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 Constructor Object Constructor[] constructors = Demo.class.getConstructors(); // Create annotation object Annotation annotation = constructors[0] .getAnnotation(PathVar.class); if (annotation instanceof PathVar) { PathVar customAnnotation = (PathVar)annotation; System.out.println( "Path: " + customAnnotation.Path()); } }} // Demo classclass Demo { public Demo(@PathVar(Path = "Demo/usr") String str) {}} // PathVar interface@Target({ ElementType.TYPE_USE })@Retention(RetentionPolicy.RUNTIME)@interface PathVar { public String Path();}
输出。
Path: Demo/usr
程序2
// Java program to demonstrate// Constructor.getAnnotation() method import java.lang.annotation.Annotation;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;import java.lang.reflect.Constructor; public class GFG { public static void main(String... args) throws NoSuchMethodException { // Create Constructor Object Constructor[] constructors = Maths.class.getConstructors(); // Create annotation object Annotation annotation = constructors[0] .getAnnotation(Calculator.class); System.out.println( "Annotation:" + annotation.toString()); }} // Demo class@Calculator(add = "Adding value", subtract = "Subtracting Value")class Maths { @Calculator(add = "Adding value", subtract = "Subtracting Value") public Maths() {}} // Calculator interface@Retention(RetentionPolicy.RUNTIME)@interface Calculator { public String add(); public String subtract();}输出。
Annotation : @Calculator(add=Adding value, subtract=Subtracting Value)
参考资料: https://docs.oracle.com/javase/10/docs/api/java/lang/reflect/Constructor.html#getAnnotation(java.lang.Class)
