JHH
JHH

Reputation: 9315

Is there a way to have method annotations passed on to sub-classes?

I have a few custom method annotations used on methods which are typically overridden. For example, let's consider something like an @Async annotation:

public class Base {
  @Async
  public void foo() {
  }
}

Is there a way to signal to the compiler and/or IDE that a method annotation should follow into overridden versions of a method, so that when someone extends Base and overrides foo(), the @Async annotation is automatically inserted, similarly to how @Override is automatically inserted by most IDEs?

If there's no general way of hinting this, is there an IntelliJ/Android Studio specific way?

Upvotes: 4

Views: 93

Answers (1)

AlexR
AlexR

Reputation: 115388

Annotation is inherited if it is marked with other annotation @Inherited. So, if annotation @Async that you have given as an example is yours just do the following:

@Inherited
// other annotations (e.g. Retention, Target etc)
@interface Async {
}

If however this is not your annotation you the only way to make it visible in subclass is to create a trivial implementation of foo() in this subclass and mark this method with this annotation, e.g.

public class Base {
  @Async
  public void foo() {
  }
}
public class Child extends Base {
  // Trivial implementation needed only to make the annotation available here. 
  @Async
  public void foo() {
      super.foo();
  }
}

Upvotes: 3

Related Questions