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()
方法。
TOP