Структура кода
Допустим, у нас есть такая структура:
class A {
@AMethodAnnotation("my-data")
public void myMethod() {
}
}
@MyClassAnnotation
class B extends A {
@Override
public void myMethod() {
}
}
Чего я пытаюсь достичь
Используя обработку аннотаций, я пытаюсь извлечь данные из аннотации AMethodAnnotation
, расположенной в методе myMethod
внутри класса A
. класс B
расширяет этот класс и переопределяет его метод myMethod
.
Суть в том, что мне нужны данные из методов с AMethodAnnotation
, если класс, в котором он находится, имеет аннотацию MyClassAnnotation
.
Я получаю классы с аннотацией MyClassAnnotation
и перебираю enclosedElements
, там я могу проверить, есть ли у него аннотация Override
, но я не уверен, как получить метод, который он переопределяет, так как именно там находится AMethodAnnotation
с данные, которые я хочу. ExecutableElement
, похоже, не предоставляет способов получить это.
for (Element classElement : roundEnv.getElementsAnnotatedWith(MyClassAnnotation.class)) {
// Make sure it's a class
if (classElement.getKind() != ElementKind.CLASS) {
continue;
}
// Loop through methods inside class
for (Element methodElement : classElement.getEnclosedElements()) {
// Make sure the element is a method & has a @Path annotation
if (methodElement.getKind() != ElementKind.METHOD) {
continue;
}
// If method has @Override annotation do stuff
}
}
Вопрос
Есть ли способ получить ссылку на метод, который переопределяется?
Есть способ: вы получаете суперкласс B
, который равен A
, и вы перебираете enclosedElements
в A
, тогда вам нужно будет проверить, совпадает ли имя метода и совпадают ли параметры и в том же порядке . Но я считаю, что этот способ требует много проверок, поэтому мой вопрос, есть ли лучший способ.