Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Annotations on Interfaces?

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

Maybe someone could give me an example?

like image 357
Allain Lalonde Avatar asked Sep 28 '08 18:09

Allain Lalonde


People also ask

Are annotations interfaces?

Annotation types are a form of interface, which will be covered in a later lesson. For the moment, you do not need to understand interfaces. The body of the previous annotation definition contains annotation type element declarations, which look a lot like methods. Note that they can define optional default values.

Can we use @component annotation in interface?

No we are following the dynamic binding and creating the object of interface but implementation is on the run time. So @autowired is the one that will create the object internally and we have @component for bubbleSortAlgo and the only candidate for the injection, so it will get reference from there.

Are annotations inherited from interface?

The annotation can be overridden in case the child class has the annotation. Because there is no multiple inheritance in Java, annotations on interfaces cannot be inherited.

What are annotations in API?

Annotations are like meta-tags that you can add to the code and apply to package declarations, type declarations, constructors, methods, fields, parameters, and variables.


2 Answers

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.

like image 108
Alex Miller Avatar answered Sep 17 '22 12:09

Alex Miller


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;
    }
    ...
}
like image 45
raspacorp Avatar answered Sep 17 '22 12:09

raspacorp