- 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.AccessibleObject.getAnnotations() 方法示例
描述
java.lang.reflect.AccessibleObject.getAnnotations() 方法返回此元素上存在的注解(如果此元素没有注解,则返回长度为 0 的数组)。此方法的调用方可以自由地修改返回的数组;它对返回给其他调用方的数组没有任何影响。
声明
以下是 java.lang.reflect.AccessibleObject.getAnnotations() 方法的声明。
public Annotation[] getAnnotations()
返回值
此元素上存在的注解。
示例
以下示例显示了如何使用 java.lang.reflect.AccessibleObject.getAnnotations() 方法。
实时演示package com.tutorialspoint;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Annotation;
import java.lang.reflect.AccessibleObject;
public class AccessibleObjectDemo {
public static void main(String[] args) throws NoSuchMethodException,
SecurityException, NoSuchFieldException {
AccessibleObject sampleMethod = SampleClass.class.getMethod("sampleMethod");
Annotation[] annotations = sampleMethod.getAnnotations();
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 = "sampleMethod", value = "Sample Method Annotation")
public String sampleMethod(){
return "sample";
}
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: sampleMethod value: Sample Method Annotation
java_reflect_accessibleobject.htm
广告