10

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.

3

3 Answers 3

15

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.

4
  • 1
    @ibrahimyilmaz, read the Javadoc for AnnotationUtils.findAnnotation.
    – alexvinall
    Jun 2, 2014 at 14:24
  • Example added @ibrahimyilmaz, also consider getting the method as described here, it seems cleaner to me.
    – superbob
    Jun 2, 2014 at 15:26
  • I know how to use method:) I cant import spring core library into my android project. I added this my gradle conf. 'org.springframework:spring-core:4.0.5.RELEASE' Jun 3, 2014 at 6:31
  • @ibrahimyilmaz, try to fix your gradle issue, if you can't ask the an appropriate question. Then see if your initial question is solved.
    – superbob
    Jun 4, 2014 at 9:41
3

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

But beware, as following post states, there are good reasons for this not to be directly implemented in Java : Why java classes do not inherit annotations from implemented interfaces?

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

2

you can't inherit annotations.

But a framework that uses an annotation can check to see if annotation is present on superclass

1
  • is it work for abstract class? if it is, I can convert interface to abstrack class Jun 2, 2014 at 12:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.