新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

java如何获取注解标注的方法,java注解获取请求参数

发布时间:2023-10-25 20:49:59

java如何获得注解标注的方法

可使用反射机制来获得注解标注的方法。

首先,需要取得要获得注解的类的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()方法。