Annotations on Interfaces?

前端 未结 10 2140
一生所求
一生所求 2020-12-08 21:52

I can\'t figure out a use case for being able to annotate interfaces in Java.

Maybe someone could give me an example?

相关标签:
10条回答
  • 2020-12-08 22:23

    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.

    0 讨论(0)
  • 2020-12-08 22:24

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

    0 讨论(0)
  • 2020-12-08 22:26

    A use case that I am working with is javax/hibernate bean validation, we are using interfaces to help us on avoiding to define validations on every specific class.

    public interface IUser {
        @NotNull Long getUserId();
        ...
    }
    
    public class WebUser implements IUser {
        private Long userId;
    
        @Override
        public Long getUserId(){
            return userId;
        }
        ...
    }
    
    0 讨论(0)
  • 2020-12-08 22:28

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

    0 讨论(0)
  • 2020-12-08 22:30

    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...

    0 讨论(0)
  • 2020-12-08 22:35

    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.

    0 讨论(0)
提交回复
热议问题