Java.lang.getDeclaredAnnotations() 方法
描述
java.lang.Package.getDeclaredAnnotations() 方法返回直接存在于该元素上的所有注释。 与此接口中的其他方法不同,此方法忽略继承的注解。 (如果此元素上没有直接存在注释,则返回长度为零的数组。)此方法的调用者可以自由修改返回的数组; 它不会影响返回给其他调用者的数组。
声明
以下是 java.lang.Package.getDeclaredAnnotations() 方法的声明。
public Annotation[] getDeclaredAnnotations()
参数
NA
返回值
此方法返回此元素上直接存在的所有注释
异常
NA
示例
下面的例子展示了 lang.Object.getDeclaredAnnotations() 方法的使用。
package com.tutorialspoint;
import java.lang.annotation.Annotation;
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 annotations
Annotation[] annotation = m.getDeclaredAnnotations();
// print the annotation
for (int i = 0; i < annotation.length; i++) {
System.out.println(annotation[i]);
}
} catch (NoSuchMethodException exc) {
exc.printStackTrace();
}
}
public static void main(String args[]) {
example();
}
}
让我们编译并运行上面的程序,这将产生下面的结果 −
@com.tutorialspoint.Demo(str=Demo Annotation, val=100)

