Java中的构造函数 getAnnotation() 方法及示例
如果存在这样的注解,则使用Constructor类的getAnnotation()方法获取指定类型的此构造函数对象注解,否则为 null。指定的类型作为参数传递。
句法:
public T
getAnnotation(Class annotationClass)
参数:该方法接受一个参数annotationClass ,它表示对应于注解类型的Class对象。
返回值:如果此元素上存在指定的注释类型,则此方法返回此元素的注释,否则返回 null。
异常:如果给定的注释类为空,此方法将抛出NullPointerException 。
下面的程序说明了 getAnnotation() 方法:
方案一:
// 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 class
class 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
方案二:
// 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: Java Java.lang.Class)