Skip to content

Commit 7efd5e5

Browse files
committed
ClassUtils: add methods to get annotated methods
These methods are analogous to the getAnnotatedFields methods, but for annotated methods rather than fields.
1 parent 8c3b9d0 commit 7efd5e5

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

src/main/java/org/scijava/util/ClassUtils.java

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
import java.lang.annotation.Annotation;
3636
import java.lang.reflect.Array;
3737
import java.lang.reflect.Field;
38+
import java.lang.reflect.Method;
3839
import java.lang.reflect.Type;
3940
import java.net.MalformedURLException;
4041
import java.net.URL;
@@ -270,6 +271,56 @@ public static URL getLocation(final Class<?> c) {
270271
}
271272
}
272273

274+
/**
275+
* Gets the given class's {@link Method}s marked with the annotation of the
276+
* specified class.
277+
* <p>
278+
* Unlike {@link Class#getMethods()}, the result will include any non-public
279+
* methods, including methods defined in supertypes of the given class.
280+
* </p>
281+
*
282+
* @param c The class to scan for annotated methods.
283+
* @param annotationClass The type of annotation for which to scan.
284+
* @return A new list containing all methods with the requested annotation.
285+
*/
286+
public static <A extends Annotation> List<Method> getAnnotatedMethods(
287+
final Class<?> c, final Class<A> annotationClass)
288+
{
289+
final ArrayList<Method> methods = new ArrayList<Method>();
290+
getAnnotatedMethods(c, annotationClass, methods);
291+
return methods;
292+
}
293+
294+
/**
295+
* Gets the given class's {@link Method}s marked with the annotation of the
296+
* specified class.
297+
* <p>
298+
* Unlike {@link Class#getMethods()}, the result will include any non-public
299+
* methods, including methods defined in supertypes of the given class.
300+
* </p>
301+
*
302+
* @param c The class to scan for annotated methods.
303+
* @param annotationClass The type of annotation for which to scan.
304+
* @param methods The list to which matching methods will be added.
305+
*/
306+
public static <A extends Annotation> void
307+
getAnnotatedMethods(final Class<?> c, final Class<A> annotationClass,
308+
final List<Method> methods)
309+
{
310+
if (c == null || c == Object.class) return;
311+
312+
// check supertypes for annotated methods first
313+
getAnnotatedMethods(c.getSuperclass(), annotationClass, methods);
314+
for (final Class<?> iface : c.getInterfaces()) {
315+
getAnnotatedMethods(iface, annotationClass, methods);
316+
}
317+
318+
for (final Method m : c.getDeclaredMethods()) {
319+
final A ann = m.getAnnotation(annotationClass);
320+
if (ann != null) methods.add(m);
321+
}
322+
}
323+
273324
/**
274325
* Gets the given class's {@link Field}s marked with the annotation of the
275326
* specified class.

0 commit comments

Comments
 (0)