Java.lang.Package.getAnnotation() 方法
描述
java.lang.Package.getAnnotation(Class<A>annotationClass) 方法返回此元素的指定类型的注释(如果存在这样的注释),否则返回 null。
声明
以下是 java.lang.Package.getAnnotation() 方法的声明。
public <A extends Annotation> A getAnnotation(Class<A> annotationClass)
参数
annotationClass − 注解类型对应的Class对象
返回值
如果此元素上存在指定的注释类型,则此方法返回此元素的注释,否则返回 null
异常
NullPointerException − 如果给定的注解类为空
IllegalMonitorStateException − 如果当前线程不是对象监视器的所有者。
示例
下面的例子展示了 lang.Object.getAnnotation() 方法的使用。
package com.tutorialspoint;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
// declare a new annotation
@Retention(RetentionPolicy.RUNTIME)
@interface Demo {
String str();
int val();
}
public class PackageDemo {
// set values for the annotation
@Demo(str = "Demo Annotation", val = 100)
// a method to call in the main
public static void example() {
PackageDemo ob = new PackageDemo();
try {
Class c = ob.getClass();
// get the method example
Method m = c.getMethod("example");
// get the annotation for class Demo
Demo annotation = m.getAnnotation(Demo.class);
// print the annotation
System.out.println(annotation.str() + " " + annotation.val());
} catch (NoSuchMethodException exc) {
exc.printStackTrace();
}
}
public static void main(String args[]) {
example();
}
}
让我们编译并运行上面的程序,这将产生下面的结果 −
Demo Annotation 100

