Serializable
is an example. Such interfaces add certain semantics to a class that are later used either through reflection (using instanceof
) or are not programmatically used at all but serve as information for developers and development tools. These are known as marker interfaces. They represent meta-information about the class.Starting with Java 1.5, a new kind of type was introduced — annotations. They take on and extend the capabilities of marker interfaces:
- Annotations can be applied not only to classes or interfaces but nearly anything: packages, methods, their parameters, and variables. The full list is presented in the enumeration ElementType.
- An annotation can carry data within its elements.
- An annotation may not be present at runtime, or may remain only in the source code, not making it into the bytecode at all. This is determined by its RetentionPolicy.
- An annotation can be made non-inheritable by simply not marking it with
@Inherited
. - And of course, the syntax. An applied annotation is easily distinguishable from real interfaces at first glance.
- A method might require a parameter to be marked, as the marker interface is also a type.
- The applicability of the marker can be limited to specific types only by making the interface an ancestor of these types.
@interface
is used to declare an annotation, while interface
is used to declare an interface.As a result of compilation, in .class file an annotation becomes an interface extending
java.lang.annotation.Annotation
, marked with the ACC_ANNOTATION
flag. Its elements turn into abstract methods. This explains the syntax of declaration. Annotation-specific attributes are described in JVMS 4.7.16-4.7.22.By the way, constructs like
@something
in Javadoc are called tags. They look similar to annotations and also represent meta-information for documentation, but technically have nothing to do with them.