How to get interface annotations or abstract class methods in Java

I have an interface like this:

public interface IFoo{ @AnnotationTest(param="test") String invoke(); } 

and I implement it as follows:

 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 annotation is unreachable...") } } } 

If you can get the parent annotation, I want to know its way.

Any help or idea would be appreciated.

+8
java
source share
3 answers

You can use Spring AnnotationUtils.findAnnotation to read annotations from interfaces.

Example:

Interface I.java

 public interface I { @SomeAnnotation void theMethod(); } 

A.java class A.java

 public class A implements I { public void theMethod() { Method method = new Object() {}.getClass().getEnclosingMethod(); SomeAnnotation ann = AnnotationUtils.findAnnotation(method, AnnotationTest.class); } } 

Obviously, you need to include class frames in your Spring project (and import).

+8
source share

you cannot inherit annotations.

But a structure using annotation can check if annotation is present for the superclass

+2
source share

There is no direct way to get it. If you really need to, you need to manually run the getInterfaces() loop to find if there is any implemented interface annotation. If you want to search for (ultimately abstract) superclasses, and the annotation is not @Inherited , you can @Inherited over the superclass chain again until you find Object (*).

But be careful, because the following message states have good reasons for not directly implementing it in Java: Why don't java classes inherit annotations from implemented interfaces?

(*) If the annotation is @Inherited , it is automatically searched on superclasses, but not on interfaces.

+1
source share

All Articles