下面是一个方法,它返回具有特定注释的方法:
public static List<Method> getMethodsAnnotatedWith(final Class<?> type, final Class<? extends Annotation> annotation) {
final List<Method> methods = new ArrayList<Method>();
Class<?> klass = type;
while (klass != Object.class) { // need to traverse a type hierarchy in order to process methods from super types
// iterate though the list of methods declared in the class represented by klass variable, and add those annotated with the specified annotation
for (final Method method : klass.getDeclaredMethods()) {
if (method.isAnnotationPresent(annotation)) {
Annotation annotInstance = method.getAnnotation(annotation);
// TODO process annotInstance
methods.add(method);
}
}
// move to the upper class in the hierarchy in search for more methods
klass = klass.getSuperclass();
}
return methods;
}
它可以很容易地修改为您的特定需求。请注意,所提供的方法遍历类层次结构,以便找到具有所需注释的方法。
以下是满足您特定需求的方法:
public static List<Method> getMethodsAnnotatedWithMethodXY(final Class<?> type) {
final List<Method> methods = new ArrayList<Method>();
Class<?> klass = type;
while (klass != Object.class) { // need to iterated thought hierarchy in order to retrieve methods from above the current instance
// iterate though the list of methods declared in the class represented by klass variable, and add those annotated with the specified annotation
for (final Method method : klass.getDeclaredMethods()) {
if (method.isAnnotationPresent(MethodXY.class)) {
MethodXY annotInstance = method.getAnnotation(MethodXY.class);
if (annotInstance.x() == 3 && annotInstance.y() == 2) {
methods.add(method);
}
}
}
// move to the upper class in the hierarchy in search for more methods
klass = klass.getSuperclass();
}
return methods;
}
有关引用找到的方法,请参阅教程。这里的潜在困难之一是方法参数的数量,这些参数在找到的方法之间可能会有所不同,因此需要一些额外的处理。