Java 如何检索特定类中存在的带注释和未带注释的方法
使用java反射Java 如何检索特定类中存在的带注释和未带注释的方法,java,jsp,annotations,Java,Jsp,Annotations,使用java反射 class A { @two public method1() { } @one public method2() { } @two public method3() { } public method4() { } } 在上面给出的代码示例中,我希望根据用户的选择检索带注释的方法、非带注释的方法以及类中存在的所有类型的方法。 例如
class A {
@two
public method1() {
}
@one
public method2() {
}
@two
public method3() {
}
public method4() {
}
}
在上面给出的代码示例中,我希望根据用户的选择检索带注释的方法、非带注释的方法以及类中存在的所有类型的方法。 例如,在上面给出的示例中,我只想检索类A的带注释的方法,或者只检索类A的非带注释的方法,或者检索类A中存在的所有方法。这个示例的代码应该是什么 有人能帮我一下吗
public static void main(String[] args) throws Exception {
Class clazz = B.class;
List<Method> allMethods = new ArrayList<Method>(Arrays.asList(clazz.getDeclaredMethods()));
try {
for (Method method : allMethods) {
method.setAccessible(true);
if (null != method.getAnnotations() && method.getAnnotations().length > 0) {
Annotation[] annotations = method.getAnnotations();
System.out.println(method.getName());
for (Annotation annotation : annotations) {
System.out.println(annotation);
}
} else {
System.out.println(method.getName());
}
}
} catch (Exception e) {
System.out.println(e);
}
}
public class B {
public void getValue() {
}
@Deprecated
public void getValue1() {
}
}
要记住的要点
1.)上述方法使用Java反射
2.java.lang.reflect.Method
有两个方法getAnnotations()
和getDeclaredAnnotations()
,可以根据需要使用。有关详细信息,请阅读Javadoc
3.)它还有isAnnotationPresent()
方法,用于检查moethod上的特定注释
4.)上述内容可用于访问字段和方法属性。搜索带注释方法的例子很多。请看这篇文章或下面的文章,至少您应该尝试一下。类和方法的javadoc有您需要知道的所有内容。
getValue
getValue1
@java.lang.Deprecated()