|
35 | 35 | import java.lang.annotation.Annotation; |
36 | 36 | import java.lang.reflect.Array; |
37 | 37 | import java.lang.reflect.Field; |
| 38 | +import java.lang.reflect.Method; |
38 | 39 | import java.lang.reflect.Type; |
39 | 40 | import java.net.MalformedURLException; |
40 | 41 | import java.net.URL; |
@@ -270,6 +271,56 @@ public static URL getLocation(final Class<?> c) { |
270 | 271 | } |
271 | 272 | } |
272 | 273 |
|
| 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 | + |
273 | 324 | /** |
274 | 325 | * Gets the given class's {@link Field}s marked with the annotation of the |
275 | 326 | * specified class. |
|
0 commit comments