How to get annotations of interface or abstract class methods in Java
java
Solution
You can use Spring AnnotationUtils.findAnnotation to read annotations from interfaces.
Example :
Interface `I.java`
public interface I {
@SomeAnnotation
void theMethod();
}
Implementing class `A.java`
public class A implements I {
public void theMethod() {
Method method = new Object() {}.getClass().getEnclosingMethod();
SomeAnnotation ann = AnnotationUtils.findAnnotation(method, AnnotationTest.class);
}
}
It obviously requires to include in your project (and import) Spring framework classes.
Problem
I have an interface like this: ``` public interface IFoo{ @AnnotationTest(param="test") String invoke(); } ``` and I implement this like this: ``` public class Foo implements IFoo{ @Override public String invoke(){ Method method = new Object() { }.getClass().getEnclosingMethod(); AnnotationTest ann = method.getAnnotation(AnnotationTest.class); if(ann == null){ System.out.printl("Parent method's annotation is unreachable...") } } } ``` If it is possible to reach parent's annotation, I want to learn the way of it. Any help or idea will be appreciated.