這裏有一個方法,它返回的具體註釋方法:
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 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
final List<Method> allMethods = new ArrayList<Method>(Arrays.asList(klass.getDeclaredMethods()));
for (final Method method : allMethods) {
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
final List<Method> allMethods = new ArrayList<Method>(Arrays.asList(klass.getDeclaredMethods()));
for (final Method method : allMethods) {
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;
}
對於發現的方法(S)的調用請參考一tutorial。這裏可能遇到的困難之一是方法參數的數量,這些參數可能因所找到的方法而異,因此需要一些額外的處理。
我想每一個代碼示例到目前爲止,我所看到的一切涉及「掃描」的所有方法 – nobody
剛擡起頭,註釋可能是在該行註釋annotInstance =方法無效。 getAnnotation(註釋); – kliron
@kliron有警衛'if(method.isAnnotationPresent(MethodXY.class))...'爲什麼'null'? – 01es