这工作得很好滤除方法与Analyze
注释:Java反射:带注释的方法数量?
for (Method m : ParseTree.class.getMethods()) {
if (m.isAnnotationPresent(Analyze.class)) {
如果我只想计数,而无需通过循环呢?是否有某种方法可以返回某个类中有多少方法具有特定的注释?
这工作得很好滤除方法与Analyze
注释:Java反射:带注释的方法数量?
for (Method m : ParseTree.class.getMethods()) {
if (m.isAnnotationPresent(Analyze.class)) {
如果我只想计数,而无需通过循环呢?是否有某种方法可以返回某个类中有多少方法具有特定的注释?
这是一个非常特殊的用例,所以我真的怀疑,Java反射API中有一个方法。
但即使有这样的方法,它也会这样做:遍历类的所有方法,计算注释并报告数量。
我建议你在这个任务的一些实用工具类中实现一个静态方法。
public static int countAnnotationsInClass(Class<?> testClass, Class<?> annotation) {
// ...
}
具有运行时保留(即可通过反射获得的那些)的Java注释只能从存在注释的元素直接访问。所以你将不得不循环遍历这些方法并检查你的例子中的注释。
如果您需要在类级别做了很多注释处理的,我建议你创建一个实用工具类,做的是:
public class AnnotationUtils {
public static int countMethodsWithAnnotation(Class<?> klass,
Class<?> annotation) {
int count = 0;
for (Method m : klass.getMethods()) {
if (m.isAnnotationPresent(annotation)) {
count++;
}
}
return count;
}
// Other methods for custom annotation processing
}
然后,您可以使用实用工具类,让你在需要的信息一种方法调用,因为您需要在其余代码中:
int count = AnnotationUtils.countMethodsWithAnnotation(ParseTree.class,
Analyze.class);
是的,真正的问题是:为什么? – 2009-12-02 16:29:05