Java Class getDeclaredAnnotations()方法
java.lang.Class.getDeclaredAnnotations() 方法返回仅在方法上声明的注释,并忽略方法继承的注释。如果没有直接在方法上声明的注释,则返回的注释数组为空。返回数组的修改将不会影响返回给其他调用者的数组。当所有返回的批注数组由不同的调用方调用时,它们彼此独立。
1 语法
public Annotation[] getDeclaredAnnotations()
2 参数
无
3 返回值
该方法返回直接存在于此元素上的注释数组
4 示例
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* Java Class getDeclaredAnnotations()方法
*/
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
import java.lang.annotation.Annotation;
// create a custom Annotation
@Retention(RetentionPolicy.RUNTIME)
@interface customAnnotation {
// This annotation has two attributes.
public String key();
public String value();
}
// create the Main Class
public class GFG {
// call Annotation for method and
// pass values for annotation
@customAnnotation(key = "AvengersLeader",
value = "CaptainAmerica")
public static void
getCustomAnnotation()
{
try {
// create class object for class name GFG
Class c = GFG.class;
// get method name getCustomAnnotation as Method object
Method[] methods = c.getMethods();
Method method = null;
for (Method m : methods) {
if (m.getName().equals("getCustomAnnotation"))
method = m;
}
// get an array of Annotations
Annotation[] annotation = method.getDeclaredAnnotations();
// get annotation from the array of annotation
// and print the details
for (Annotation a : annotation) {
customAnnotation self = (customAnnotation)a;
// Print annotation attribute
System.out.println("Annotation details");
System.out.println("key: " + self.key());
System.out.println("value: " + self.value());
}
}
catch (Exception e) {
e.printStackTrace();
}
}
// create main method
public static void main(String args[])
{
getCustomAnnotation();
}
}
输出结果为:
Annotation details
key: AvengersLeader
value: CaptainAmerica
热门文章
优秀文章