views:

263

answers:

2

This works fine for filtering out methods with the Analyze annotation:

 for (Method m : ParseTree.class.getMethods()) {
  if (m.isAnnotationPresent(Analyze.class)) {

What if I just want a count, without looping through? Is there some method that returns how many methods in a certain class have a certain annotation?

+2  A: 

That's a very special use case, so I really doubt, there's a method in the Java reflection API.

But even if there was such a method, it simply would do the same: iterate over all methods of a class, count the annotations and report the number.

I suggest you just implement a static method in some utility class for this task.

public static int countAnnotationsInClass(Class<?> testClass, Class<?> annotation) {
  // ...
}
Andreas_D
Yes, the real question is: Why??
Tom Hawtin - tackline
A: 

Java annotations with runtime retention (that is those you can get through reflection) are only accessible directly from the element on which the annotation is present. So you are going to have to loop through the methods and check for the annotations like you have in your example.

If you need to do a lot of annotation processing at the class level I suggest you create a utility class that does that:

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

}

You could then use the utility class to get the information you want in one method call as you require in the rest of your code:

int count = AnnotationUtils.countMethodsWithAnnotation(ParseTree.class,
                                                       Analyze.class);
Tendayi Mawushe