溫馨提示×

java怎么獲取注解標注的方法

小億
219
2023-10-25 20:49:59
欄目: 編程語言

可以使用反射機制來獲取注解標注的方法。

首先,需要獲得要獲取注解的類的Class對象,可以通過類名.class或者對象.getClass()方法來獲取。然后,通過Class對象的getMethods()方法來獲取該類的所有公共方法。接著,遍歷這些方法,可以通過Method對象的getAnnotation()方法來獲取方法上的指定注解。

以下是一個示例代碼:

import java.lang.reflect.Method;

public class AnnotationExample {

    @MyAnnotation
    public void myMethod() {
        // 方法體
    }

    public static void main(String[] args) throws NoSuchMethodException {
        Class<AnnotationExample> clazz = AnnotationExample.class;
        Method[] methods = clazz.getMethods();

        for (Method method : methods) {
            if (method.isAnnotationPresent(MyAnnotation.class)) {
                MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
                System.out.println("Method " + method.getName() + " has annotation " + annotation.value());
            }
        }
    }

}

在上面的代碼中,定義了一個自定義注解@MyAnnotation,然后在myMethod()方法上使用了該注解。在main方法中,通過反射獲取了AnnotationExample類的所有方法,并判斷每個方法是否有@MyAnnotation注解,如果有,則打印出方法名和注解值。

注意:獲取到的方法包括了父類中的方法,如果只想獲取當前類中的方法,可以使用getDeclaredMethods()方法。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女