Aquí es un método que devuelve métodos con anotaciones específicas:
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;
}
Puede ser modificado fácilmente a sus necesidades específicas. Por favor tenga en cuenta que el método proporcionado atraviesa la jerarquía de clases para encontrar métodos con anotaciones requeridas.
Aquí es un método para sus necesidades específicas:
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;
}
para la invocación del método (s) encontrado pls refieren una tutorial. Una de las posibles dificultades aquí es la cantidad de argumentos de métodos, que pueden variar entre los métodos encontrados y, por lo tanto, requieren algún procesamiento adicional.
Supongo que cada ejemplo de código que he visto hasta ahora involucra a todos "exploración" todos los métodos – nobody
Sólo una cabeza, anotación podría ser nula en la línea de anotación annotInstance = método. getAnnotation (anotación); – kliron
@kliron Hay guard 'if (method.isAnnotationPresent (MethodXY.class)) ... '¿por qué' null'? – 01es