1

I am trying to do this, I have some "base" annotation

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.ANNOTATION_TYPE})
public @interface A
{

}

and I have annotaion B which is annotated by A

@A
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD })
public @interface B {

    String value();
}

I want to have interface which behaves something like this, being sure that T is annotation which is annotated by A.

interface SomeInterface<T extends A>
{
    void method(T argument);
}

So that I implement that something like this

public class Implementation implements SomeInterface<B>
{
    public void method(B argument);
}

How to do that? When I use "T extends A" in SomeInterface, when I implement that, it says that B is not a valid substitue.

Thanks!

stewenson
  • 1,282
  • 3
  • 15
  • 34

2 Answers2

3

B is not a valid substitution for <T extends A> because B does not extend A.

Java does not include a way to require that a generic type parameter has a particular annotation.

If you can refactor SomeInterface to be a class instead of an interface, you could put a runtime check in the constructor:

protected SomeInterface(Class<T> classOfT) {
    if(classOfT.getAnnotation(A.class) == null)
        throw new RuntimeException("T must be annotated with @A");
}
user253751
  • 57,427
  • 7
  • 48
  • 90
2

Annotation inheritance is not possible in Java.

What you have written is simply an annotation annotated by another annotation, not an annotation extending another one.

If annotation inheritance would have been possible, I guess it would have been something like this:

public @interface B extends A {

    String value();
}

But it just does not exist.

Check also this link and this link

Community
  • 1
  • 1
Guillaume Polet
  • 47,259
  • 4
  • 83
  • 117