What is the advantage of using annotations by interface type?

In this example, below the 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(); } 

compiles 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(); } 

Thus, the annotation type is compiled to the interface type before execution starts.

In java: What is the advantage of using annotation type ( @interface ) as interface ?

+5
source share
2 answers

Interfaces is an object modeling technique that allows objects to implement behavior (but not state) associated with several types.

Annotations are a method for embedding typed metadata in your code; this metadata is intended for use by tools (test frameworks, code generators, etc.), but they do not have language level semantics. You can think of them as structured / typed comments attached to specific program elements that can be accessed through reflection.

Under the hood, annotations are implemented as interfaces, mostly as a matter of convenience, but the similarities are probably more confusing than useful for understanding what they are intended for.

+6
source

If you manually do what the compiler did, you are not defining an annotation. According to Oracle documentation ,

an interface that manually extends [ java.lang.annotation.Annotation ] does not determine the type of annotation.

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

+5
source

All Articles