Reputation: 1
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?
Upvotes: 5
Views: 1093
Reputation: 95346
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.
Upvotes: 6
Reputation: 726539
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.
Upvotes: 5