Code structure
Let's say we have a structure like this:
class A {
@AMethodAnnotation("my-data")
public void myMethod() {
}
}
@MyClassAnnotation
class B extends A {
@Override
public void myMethod() {
}
}
What I'm trying to achieve
Using annotation processing I'm trying to extract data from the annotation AMethodAnnotation located on the method myMethod inside class A. class B extends this class and overrides it's method myMethod.
The twist is that I want data from methods with AMethodAnnotation if the class it's inside has the annotation MyClassAnnotation.
I'm getting the classes with annotation MyClassAnnotation and looping through the enclosedElements, there I can check if it has the Override annotation, but I'm not sure how to get the method it's overriding, since that is where the AMethodAnnotation is located with the data I want. ExecutableElement does not appear to provide methods to get this.
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
}
}
The question
Is there a way to get a reference to the method which is being overridden?
There is a way, you get the superclass of B which is A and you loop through the enclosedElements in A, then you would have to verify if the method name is the same, and if the parameters are the same and are in the same order. But I find this way to require a lot of checking, hence my question if there's a better way.
I wrote the following method based on the link @rmuller posted in the comments. There's extensive documentation for this method as seen in the Javadoc and the image below, in which it's more readable.