- java.lang.reflect 包類
- java.lang.reflect - 主頁
- java.lang.reflect - AccessibleObject
- 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 - 異常
- java.lang.reflect - 錯誤
- java.lang.reflect 實用資源
- java.lang.reflect - 快速指南
- java.lang.reflect - 實用資源
- java.lang.reflect - 討論
java.lang.reflect.Method.getAnnotation() 方法示例
說明
java.lang.reflect.Method.getAnnotation(Class<T> annotationClass) 方法會返回此元素的給定型別註釋(如果存在),否則返回 null。
宣告
以下是 java.lang.reflect.Method.getAnnotation(Class<T> annotationClass) 方法的宣告。
public <T extends Annotation> T getAnnotation(Class<T> annotationClass)
引數
annotationClass − 對應於註釋型別的 Class 物件。
返回
此元素上當前註釋型別的此元素的註釋(如果存在),否則返回 null。
異常
空指標異常 − 如果給定的註釋類為 null。
示例
以下示例演示了 java.lang.reflect.Method.getAnnotation(Class<T> annotationClass) 方法的用法。
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 annotation = methods[0].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="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
廣告