Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the advantage of using annotation over interface type?

In this example, below annotation type(@interface):

@interface ClassPreamble {
       String author();
       String date();
       int currentRevision() default 1;
       String lastModified() default "N/A";
       String lastModifiedBy() default "N/A";
       // Note use of array
       String[] reviewers();
    }

gets compiled to interface type:

interface annotationtype.ClassPreamble extends java.lang.annotation.Annotation{
    public abstract java.lang.String author();
    public abstract java.lang.String date();
    public abstract int currentRevision();
    public abstract java.lang.String lastModified();
    public abstract java.lang.String lastModifiedBy();
    public abstract java.lang.String[] reviewers();
}

So, the annotation type is getting compiled to interface type, before runtime.

In java, What is the advantage of using annotation type(@interface) over the interface type?

like image 642
overexchange Avatar asked Jun 27 '15 10:06

overexchange


2 Answers

Interfaces are a technique for object modeling, that allow objects to implement behaviors (but not state) associated with multiple types.

Annotations are a technique for embedding typed metadata in your code; this metadata is intended to be consumed by tools (test frameworks, code generators, etc), but they have no language-level semantics. You could think of them as structured/typed comments attached to certain program elements, that can be accessed via reflection.

Under the hood, annotations are implemented as interfaces, largely as a matter of convenience, but the similarity is probably more confusing than helpful in understanding what they are for.

like image 108
Brian Goetz Avatar answered Oct 27 '22 00:10

Brian Goetz


If you do manually what compiler did automatically, you would not define an annotation. According to Oracle documentation,

an interface that manually extends [java.lang.annotation.Annotation] does not define an annotation type.

Therefore, @interface syntax is required to define an annotation in Java.

like image 37
Sergey Kalinichenko Avatar answered Oct 27 '22 00:10

Sergey Kalinichenko