- java.lang.reflect 包类
- java.lang.reflect - 主页
- java.lang.reflect - AccessibleObject
- java.lang.reflect - Array
- java.lang.reflect - Constructor<T>
- java.lang.reflect - Field
- java.lang.reflect - Method
- java.lang.reflect - Modifier
- java.lang.reflect - Proxy
- java.lang.reflect 包额外信息
- java.lang.reflect - 接口
- java.lang.reflect - 例外
- java.lang.reflect - 错误
- java.lang.reflect 有用资源
- java.lang.reflect - 快速指南
- java.lang.reflect - 有用资源
- java.lang.reflect - 讨论
java.lang.reflect.Method.getDeclaredAnnotations() 方法示例
描述
java.lang.reflect.Method.getDeclaredAnnotations() 方法返回该元素上直接存在的所有注释。此方法与本接口中的其他方法不同,它会忽略继承的注释。(如果此元素上直接不存在注释,则返回长度为零的数组。)此方法的调用方可以修改返回的数组;这不会对返回给其他调用方的数组产生任何影响。
声明
以下是 java.lang.reflect.Method.getDeclaredAnnotations() 方法的声明。
public Annotation[] getDeclaredAnnotations()
返回
此元素上直接存在的所有注释。
示例
以下示例展示了 java.lang.reflect.Method.getDeclaredAnnotations() 方法的用法。
在线演示package com.tutorialspoint;
import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
public class MethodDemo {
public static void main(String[] args) {
Method[] methods = SampleClass.class.getMethods();
Annotation[] annotations = methods[0].getDeclaredAnnotations();
for(Annotation annotation : annotations){
if(annotation instanceof CustomAnnotation){
CustomAnnotation customAnnotation = (CustomAnnotation) annotation;
System.out.println("name: " + customAnnotation.name());
System.out.println("value: " + customAnnotation.value());
}
}
}
}
@CustomAnnotation(name = "SampleClass", value = "Sample Class Annotation")
class SampleClass {
private String sampleField;
@CustomAnnotation(name="getSampleMethod", value = "Sample Method Annotation")
public String getSampleField() {
return sampleField;
}
public void setSampleField(String sampleField) {
this.sampleField = sampleField;
}
}
@Retention(RetentionPolicy.RUNTIME)
@interface CustomAnnotation {
public String name();
public String value();
}
让我们编译并运行以上程序,将生成以下结果 −
name: getSampleMethod value: Sample Method Annotation
java_reflect_method.htm
广告