4

I think this is not possible, but maybe I'm wrong. So I ask you, if it is possible. ;-)

If I define a annotation that accept only class references which extends some interface or class that is possible:

 Class<? extends ServiceProviderIF> serviceIFProvider(); 

At this annotation I only can add some class which extends ServiceProviderIF. My question: is such a definition also possible for another annotation? That means with pseudocode something like this

 Class<? contains AnnotationXYZ> classReferences(); 

AnnotationXYZ is another annotation definition. And the class which should be added is only accepted by containing this Annotation.

TIA and best regards, Oli

2 Answers 2

4

It's impossible. Annotation can be set on any type (class, interface), but Java method can't return a multi-type containing types from different hierarchies. In other words, you should place all your classes that have annotation AnnotationXYZ in the same hierarchy under some interface or class Blabla, then use type <? extends Blabla> wildcard.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the hint, but that make the process more complicated and adds IMHO no benefit. The reason is to ensure that all elements inside this annotation list will have a specific annotation X (this annotation X have some additional information). So if the class extends a special interface there is no benefit for take care to add only classes with this annotation. Or I'm wrong? Best regards, Oli
Method return type specifies some kind of contract between caller and callee. AFAIK, annotations are not designed for use in contracts.
4

No, it's not possible. Only types are accepted in generic types. And annotations don't define types.

3 Comments

Hello, thanks for your answer. The syntax is only pseudocode. Some other syntax is also welcome to get a solution ... for example: Class<?> classReferences() with AnnotationXYZ;
There is no notation that can allow you to do that. Only runtime checks.
Thanks JB Nizet, thats the way I do it at the moment. But the information about the Annotation needs to be present at JVM (@Retention(RetentionPolicy.RUNTIME)). Thats not that nice, but if there is no other way to do that it's "best practise". Thanks and greetings, Oli

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.