Annotation[] getAnnotations()
描述 (Description)
java.lang.Package.getAnnotations()方法返回此元素上存在的所有注释。 (如果此元素没有注释,则返回长度为零的数组。)此方法的调用者可以自由修改返回的数组; 它对返回给其他调用者的数组没有影响。
声明 (Declaration)
以下是java.lang.Package.getAnnotations()方法的声明public Annotation[] getAnnotations()
参数 (Parameters)
NA
返回值 (Return Value)
此方法返回此元素上存在的所有注释
异常 (Exception)
NA
例子 (Example)
以下示例显示了lang.Object.getAnnotations()方法的用法。package com.iowiki;
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.getAnnotations();
// 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.iowiki.Demo(str=Demo Annotation, val=100)