JVM Knowledge

Several annotation interfaces are predefined in the Java SE Platform API. Some of the predefined annotation interfaces have special semantics in the Java programming language and require special behavior on the part of a Java compiler, as specified in this section. This section does not provide a complete specification for the predefined annotation interfaces, for which the reader is referred to the Java SE Platform API documentation (§1.4).

9.6.4.1. @Target

An annotation of type java.lang.annotation.Target is used on the declaration of an annotation interface A to specify the contexts in which A is applicable. java.lang.annotation.Target has a single element, value, of type java.lang.annotation.ElementType[], to specify contexts.

Annotation interfaces may be applicable in declaration contexts, where annotations apply to declarations, or in type contexts, where annotations apply to types used in declarations and expressions.

There are ten declaration contexts, each corresponding to an enum constant of java.lang.annotation.ElementType:

  1. Module declarations (§7.7)

    Corresponds to java.lang.annotation.ElementType.MODULE

  2. Package declarations (§7.4.1)

    Corresponds to java.lang.annotation.ElementType.PACKAGE

  3. Class declarations (including enum declarations and record declarations) and interface declarations (including annotation interface declarations) (§8.1.1, §8.5, §8.9, §8.10, §9.1.1, §9.5, §9.6)

    Corresponds to java.lang.annotation.ElementType.TYPE

    Additionally, annotation interface declarations correspond to java.lang.annotation.ElementType.ANNOTATION_TYPE

  4. Method declarations (including elements of annotation interfaces) (§8.4.3, §9.4, §9.6.1)

    Corresponds to java.lang.annotation.ElementType.METHOD

  5. Constructor declarations (§8.8.3)

    Corresponds to java.lang.annotation.ElementType.CONSTRUCTOR

  6. Type parameter declarations of generic classes, interfaces, methods, and constructors (§8.1.2, §9.1.2, §8.4.4, §8.8.4)

    Corresponds to java.lang.annotation.ElementType.TYPE_PARAMETER

  7. Field declarations (including enum constants) (§8.3.1, §9.3, §8.9.1)

    Corresponds to java.lang.annotation.ElementType.FIELD

  8. Formal and exception parameter declarations (§8.4.1, §9.4, §14.20)

    Corresponds to java.lang.annotation.ElementType.PARAMETER

  9. Local variable declarations in statements (§14.4.2, §14.14.1, §14.14.2, §14.20.3) and in patterns (§14.30.1)

    Corresponds to java.lang.annotation.ElementType.LOCAL_VARIABLE

  10. Record component declarations (§8.10.1)

    Corresponds to java.lang.annotation.ElementType.RECORD_COMPONENT

There are 17 type contexts (§4.11), all represented by the enum constant TYPE_USE of java.lang.annotation.ElementType.

It is a compile-time error if the same enum constant appears more than once in the value element of an annotation of type java.lang.annotation.Target.

If an annotation of type java.lang.annotation.Target is not present on the declaration of an annotation interface A, then A is applicable in all declaration contexts and in no type contexts.

9.6.4.2. @Retention

Annotations may be present only in source code, or they may be present in the binary form of a class or interface. An annotation that is present in the binary form may or may not be available at run time via the reflection libraries of the Java SE Platform. The annotation interface java.lang.annotation.Retention is used to choose among these possibilities.

If an annotation a corresponds to an annotation interface A, and A has a (meta-)annotation m that corresponds to java.lang.annotation.Retention, then:

  • If m has an element whose value is java.lang.annotation.RetentionPolicy.SOURCE, then a Java compiler must ensure that a is not present in the binary representation of the class or interface in which a appears.

  • If m has an element whose value is java.lang.annotation.RetentionPolicy.CLASS or java.lang.annotation.RetentionPolicy.RUNTIME, then a Java compiler must ensure that a is represented in the binary representation of the class or interface in which a appears, unless a annotates a local variable declaration or a annotates a formal parameter declaration of a lambda expression.

    An annotation on the declaration of a local variable, or on the declaration of a formal parameter of a lambda expression, is never retained in the binary representation. In contrast, an annotation on the type of a local variable, or on the type of a formal parameter of a lambda expression, is retained in the binary representation if the annotation interface specifies a suitable retention policy.

    Note that it is not illegal for an annotation interface to be meta-annotated with @Target(java.lang.annotation.ElementType.LOCAL_VARIABLE) and @Retention(java.lang.annotation.RetentionPolicy.CLASS) or @Retention(java.lang.annotation.RetentionPolicy.RUNTIME).

    If m has an element whose value is java.lang.annotation.RetentionPolicy.RUNTIME, the reflection libraries of the Java SE Platform must make a available at run time.

If A does not have a (meta-)annotation that corresponds to java.lang.annotation.Retention, then a Java compiler must treat A as if it has a (meta-)annotation that corresponds to java.lang.annotation.Retention with an element whose value is java.lang.annotation.RetentionPolicy.CLASS.

9.6.4.3. @Inherited

The annotation interface java.lang.annotation.Inherited is used to indicate that annotations on a class C corresponding to a given annotation interface are inherited by subclasses of C.

9.6.4.4. @Override

Programmers occasionally overload a method declaration when they mean to override it, leading to subtle problems. The annotation interface Override supports early detection of such problems.

The classic example concerns the equals method. Programmers write the following in class Foo:

public boolean equals(Foo that) { ... }

when they mean to write:

public boolean equals(Object that) { ... }

This is perfectly legal, but class Foo inherits the equals implementation from Object, which can cause some subtle bugs.

If a method declaration in class or interface Q is annotated with @Override, then one of the following three conditions must be true, or a compile-time error occurs:

  • the method overrides from Q a method declared in a supertype of Q (§8.4.8.1, §9.4.1.1)
  • the method is override-equivalent to a public method of Object (§4.3.2, §8.4.2)
  • Q is a record class (§8.10), and the method is an accessor method for a record component of Q (§8.10.3)

This behavior differs from Java SE 5.0, where @Override only caused a compile-time error if applied to a method that implemented a method from a superinterface that was not also present in a superclass.

The clause about overriding a public method of Object is motivated by use of @Override in an interface. Consider the following declarations:

class Foo     { @Override public int hashCode() {..} }
interface Bar { @Override int hashCode(); }

The use of @Override in the class declaration is legal by the first clause, because Foo.hashCode overrides from Foo the method Object.hashCode.

For the interface declaration, consider that an interface has public abstract members which correspond to the public members of Object (§9.2). If an interface chooses to declare them explicitly (that is, to declare members that are override-equivalent to public methods of Object), then the interface is deemed to override them, and use of @Override is allowed.

However, consider an interface that attempts to use @Override on a clone method: (finalize could also be used in this example)

interface Quux { @Override Object clone(); }

Because Object.clone is not public, there is no member called clone implicitly declared in Quux. Therefore, the explicit declaration of clone in Quux is not deemed to "implement" any other method, and it is erroneous to use @Override. (The fact that Quux.clone is public is not relevant.)

In contrast, a class declaration that declares clone is simply overriding Object.clone, so is able to use @Override:

class Beep { @Override protected Object clone() {..} }

The clause about a record class is due to the special meaning of @Override in a record declaration. Namely, it can be used to specify that a method declaration is an accessor method for a record component. Consider the following record declaration:

record Roo(int x) {
    @Override
    public int x() {
        return Math.abs(x);
    }
}

The use of @Override on the accessor method int x() ensures that if the record component x is modified or removed, then the corresponding accessor method must be modified or removed too.

9.6.4.5. @SuppressWarnings

Java compilers are increasingly capable of issuing helpful "lint-like" warnings. To encourage the use of such warnings, there should be some way to disable a warning in a part of the program when the programmer knows that the warning is inappropriate.

The annotation interface SuppressWarnings supports programmer control over warnings otherwise issued by a Java compiler. It defines a single element that is an array of String.

If a declaration is annotated with @SuppressWarnings(value = {S_1, ..., S_k}), then a Java compiler must suppress (that is, not report) any warning specified by one of S_1 ... S_k if that warning would have been generated as a result of the annotated declaration or any of its parts.

The Java programming language defines four kinds of warnings that can be specified by @SuppressWarnings:

Any other string specifies a non-standard warning. A Java compiler must ignore any such string that it does not recognize.

Compiler vendors are encouraged to document the strings they support for @SuppressWarnings, and to cooperate to ensure that the same strings are recognized across multiple compilers.

9.6.4.6. @Deprecated

Programmers are sometimes discouraged from using certain program elements (modules, classes, interfaces, fields, methods, and constructors) because they are considered dangerous or because a better alternative exists. The annotation interface Deprecated allows a compiler to warn about uses of these program elements.

A deprecated program element is a module, class, interface, field, method, or constructor whose declaration is annotated with @Deprecated. The manner in which a program element is deprecated depends on the value of the forRemoval element of the annotation:

  • If forRemoval=false (the default), then the program element is ordinarily deprecated.

    An ordinarily deprecated program element is not intended to be removed in a future release, but programmers should nevertheless migrate away from using it.

  • If forRemoval=true, then the program element is terminally deprecated.

    A terminally deprecated program element is intended to be removed in a future release. Programmers should stop using it or risk source and binary incompatibilities (§13.2) when upgrading to a newer release.

A Java compiler must produce a deprecation warning when an ordinarily deprecated program element is used (overridden, invoked, or referenced by name) in the declaration of a program element (whether explicitly or implicitly declared), unless:

  • The use is within a declaration that is itself deprecated, either ordinarily or terminally; or
  • The use is within a declaration that is annotated to suppress deprecation warnings (§9.6.4.5); or
  • The declaration where the use appears and the declaration of the ordinarily deprecated program element are both within the same outermost class; or
  • The use is within an import declaration that imports the ordinarily deprecated class, interface, or member; or
  • The use is within an exports or opens directive (§7.7.2).

A Java compiler must produce a removal warning when a terminally deprecated program element is used (overridden, invoked, or referenced by name) in the declaration of a program element (whether explicitly or implicitly declared), unless:

  • The use is within a declaration that is annotated to suppress removal warnings (§9.6.4.5); or
  • The declaration where the use appears and the declaration of the terminally deprecated program element are both within the same outermost class; or
  • The use is within an import declaration that imports the terminally deprecated class, interface, or member; or
  • The use is within an exports or opens directive.

Terminal deprecation is sufficiently urgent that the use of a terminally deprecated element will cause a removal warning even if the using element is itself deprecated, since there is no guarantee that both elements will be removed at the same time. To dismiss the warning but continue using the element, the programmer must manually acknowledge the risk via an @SuppressWarnings annotation.

No deprecation warning or removal warning is produced when:

  • a local variable or formal parameter is used (referenced by name), even if the declaration of the local variable or formal parameter is annotated with @Deprecated.
  • the name of a package is used (referenced by a qualified type name, or an import declaration, or an exports or opens directive), even if the declaration of the package is annotated with @Deprecated.
  • the name of a module is used by a qualified exports or opens directive, even if the declaration of the friend module is annotated with @Deprecated.

A module declaration that exports or opens a package is usually controlled by the same programmer or team that controls the package's declaration. As such, there is little benefit in warning that the package declaration is annotated with @Deprecated when the package is exported or opened by the module declaration. In contrast, a module declaration that exports or opens a package to a friend module is usually not controlled by the same programmer or team that controls the friend module. Simply exporting or opening the package does not make the module declaration rely on the friend module, so there is little value in warning if the friend module is deprecated; the programmer of the module declaration would almost always wish to suppress such a warning.

The only implicit declaration that can cause a deprecation warning or removal warning is a container annotation (§9.7.5). Namely, if T is a repeatable annotation interface and TC is its containing annotation interface, and TC is deprecated, then repeating the @T annotation will cause a warning. The warning is due to the implicit @TC container annotation. It is strongly discouraged to deprecate a containing annotation interface without deprecating the corresponding repeatable annotation interface.

9.6.4.7. @SafeVarargs

A variable arity parameter with a non-reifiable element type (§4.7) can cause heap pollution (§4.12.2) and give rise to compile-time unchecked warnings (§5.1.9). However, such warnings are uninformative if the body of the variable arity method is well-behaved with respect to the variable arity parameter.

The annotation interface SafeVarargs, when used to annotate a method or constructor declaration, makes a programmer assertion that prevents a Java compiler from reporting unchecked warnings for the declaration or invocation of a variable arity method or constructor where the compiler would otherwise do so due to the variable arity parameter having a non-reifiable element type.

The annotation @SafeVarargs has non-local effects because it suppresses unchecked warnings at method invocation expressions, in addition to an unchecked warning pertaining to the declaration of the variable arity method itself (§8.4.1). In contrast, the annotation @SuppressWarnings("unchecked") has local effects because it only suppresses unchecked warnings pertaining to the declaration of a method.

The canonical target for @SafeVarargs is a method like java.util.Collections.addAll, whose declaration starts with:

public static <T> boolean
  addAll(Collection<? super T> c, T... elements)

The variable arity parameter has declared type T[], which is non-reifiable. However, the method fundamentally just reads from the input array and adds the elements to a collection, both of which are safe operations with respect to the array. Therefore, any compile-time unchecked warnings at method invocation expressions for java.util.Collections.addAll are arguably spurious and uninformative. Applying @SafeVarargs to the method declaration prevents generation of these unchecked warnings at the method invocation expressions.

It is a compile-time error if a fixed arity method or constructor declaration is annotated with the annotation @SafeVarargs.

It is a compile-time error if a variable arity method declaration that is neither static nor final nor private is annotated with the annotation @SafeVarargs.

Since @SafeVarargs is only applicable to static methods, final and/or private instance methods, and constructors, the annotation is not usable where method overriding occurs. Annotation inheritance only works for annotations on classes (not on methods, interfaces, or constructors), so an @SafeVarargs-style annotation cannot be passed through instance methods in classes or through interfaces.

9.6.4.8. @Repeatable

The annotation interface java.lang.annotation.Repeatable is used on the declaration of a repeatable annotation interface to indicate its containing annotation interface (§9.6.3).

Note that an @Repeatable meta-annotation on the declaration of A, indicating AC, is not sufficient to make AC the containing annotation interface of A. There are numerous well-formedness rules for AC to be considered the containing annotation interface of A.

9.6.4.9. @FunctionalInterface

The annotation interface FunctionalInterface is used to indicate that an interface is meant to be a functional interface (§9.8). It facilitates early detection of inappropriate method declarations appearing in or inherited by an interface that is meant to be functional.

It is a compile-time error if an interface declaration is annotated with @FunctionalInterface but is not, in fact, a functional interface.

Because some interfaces are functional incidentally, it is not necessary or desirable that all declarations of functional interfaces be annotated with @FunctionalInterface.