共計 1009 個字符,預(yù)計需要花費 3 分鐘才能閱讀完成。
要獲取方法上的注解,可以使用 Java 的反射機制。以下是一種常見的方法:
- 首先,使用
Class
類的getMethod
或getDeclaredMethod
方法獲取要獲取注解的方法。getMethod
方法可以獲取公共方法,而getDeclaredMethod
方法可以獲取所有方法,包括私有方法。
Class clazz = MyClass.class;
Method method = clazz.getDeclaredMethod("myMethod");
- 然后,使用
Method
類的getAnnotation
方法獲取方法上的注解。getAnnotation
方法接收一個注解的類型作為參數(shù),并返回該注解的實例。如果方法上沒有該注解,getAnnotation
方法將返回null
。
MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
- 最后,可以通過注解對象的方法來獲取注解的屬性值。
String value = annotation.value();
完整的示例代碼如下:
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface MyAnnotation {String value();
}
class MyClass {@MyAnnotation("Hello")
public void myMethod() {// 方法體}
}
public class Main {public static void main(String[] args) throws NoSuchMethodException {
Class clazz = MyClass.class;
Method method = clazz.getDeclaredMethod("myMethod");
MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
String value = annotation.value();
System.out.println(value); // 輸出:Hello
}
}
需要注意的是,注解的保留策略需要設(shè)置為RetentionPolicy.RUNTIME
,才能在運行時通過反射獲取到注解。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完