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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With