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!

1
  • Why are you trying to do this? AFAIK, the only way to implement this would be with reflection. Commented Jan 22, 2015 at 22:43

2 Answers 2

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"); } 
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.