views:

901

answers:

7

I can't for the life of me figure out a use case for being able to annotate interfaces in Java.

Maybe someone smarter than I am could give me an example?

+1  A: 

More an example, but Local and Remote annotations in EJB3. According to the java doc,

When used on an interface, designates that interface as a local business interface.

I guess the use case here is that the interface has a special function best denoted by an annotation.

sblundy
+6  A: 

I've used it in Spring to annotate interfaces where the annotation should apply to all subclasses. For example, say you have a Service interface and you might have multiple implementations of the interface but you want a security annotation to apply regardless of the annotation. In that case, it makes the most sense to annotate the interface.

Alex Miller
More specifically is @Transactional, which you can apply to a Spring bean class, any of its methods, or the interface or interface methods which the class implements, whiever makes best sense at the time.
skaffman
A: 

You could use it for contract style programming - go one step further than just defining the interface (types and method names) and also define some semantics (contents of the types, preconditions, postconditions).

I'd have to check up on how annotations work in Java though, but this stuff could easily be done with Python annotations...

Daren Thomas
A: 

I use findbugs extensively. I find the use of annotations to specify Nullity constraints very useful. Even if you dont actually use findbugs, it makes the intent of the code much clearer. Those annotations have their place on Interfaces as much as Classes. You could argue that it is kind of programming by contract ...

+1  A: 

I've seen a lot of research tools use method annotations to allow users to specify protocols, restrictions, etc. to facilitate automatic checking later.

Since annotations don't dictate what you can do with them, there is no good reason not to allow users to annotate interfaces.

Uri
+1  A: 

Even without examples, it should be clear to explain - interfaces describe behaviour, and and so can annotations, so it's a logical match to put them together.

skaffman
A: 

When deploying applications under JBoss you can use annotations on a interface to export a service in the jmx-console.