温馨提示×

java怎么获取注解标注的方法

小亿
118
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