Ну, простыми словами:
Вы пытаетесь получить доступ к объекту, который не создан или в настоящее время не находится в памяти.
Итак, как это решить:
if (i == null) {
// Handle this
}
Поиск по имени означает, что некоторые фреймворки позволяют использовать FIndObjects с помощью строк, а код может выглядеть так: FindObject («ObjectName»);
Вот метод, который возвращает методы с конкретными аннотациями:
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) PLS ссылаются на учебник . Одной из потенциальных трудностей здесь является количество аргументов метода, которые могут варьироваться между найденными методами и, следовательно, требуют некоторой дополнительной обработки.