- 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.getAnnotation() 方法示例
描述
如果此元素中存在指定的类型的注释,则 java.lang.reflect.AccessibleObject.getAnnotation(Class
声明
以下是 java.lang.reflect.AccessibleObject.getAnnotation(Class
public <T extends Annotation> T getAnnotation(Class<T> annotationClass)
参数
annotationClass − 与注释类型对应的 Class 对象。
返回值
如果此元素存在指定注释类型,则返回此元素对指定注释类型的注释,否则返回 null。
异常
NullPointerException − 如果给定的注释类为 null。
示例
以下示例展示了如何使用 java.lang.reflect.AccessibleObject.getAnnotation(Class
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 annotation = sampleMethod.getAnnotation(CustomAnnotation.class);
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
广告