Java Annotations: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 20: Line 20:
@Retention(RetentionPolicy.RUNTIME)
@Retention(RetentionPolicy.RUNTIME)
</syntaxhighlight>
</syntaxhighlight>
@Retention is a meta-annotation
Expresses the annotation retention policy. The constants of this type describe various policies for retaining annotations


Possible values:
Possible values:
Line 26: Line 30:
* RetentionPolicy.RUNTIME: Annotations are to be recorded in the class file by the compiler and retained by the VM at run time, so they may be read reflectively.
* RetentionPolicy.RUNTIME: Annotations are to be recorded in the class file by the compiler and retained by the VM at run time, so they may be read reflectively.


@Target({ElementType.METHOD})       // This annotation can only be applied to class methods.
==@Target==
 
<syntaxhighlight lang='java'>
@Target({ElementType.METHOD})
</syntaxhighlight>
 
      // This annotation can only be applied to class methods.


The compiler reserves a set of special annotations (including [[@Deprecated]], [[@Override]] and @[[SuppressWarnings]]) for syntactic purposes.
The compiler reserves a set of special annotations (including [[@Deprecated]], [[@Override]] and @[[SuppressWarnings]]) for syntactic purposes.

Revision as of 03:06, 1 November 2018

Internal

Overview

Custom Annotations

Annotation type declarations are similar to normal interface declarations. An at-sign (@) precedes the interface keyword.

Each method declaration defines an element of the annotation type. Method declarations must not have any parameters or a throws clause. Return types are restricted to primitives, String, Class, enums, annotations, and arrays of the preceding types.

Methods can have default values.

Annotations themselves may be annotated to indicate where and when they can be used"

@Retention

@Retention(RetentionPolicy.RUNTIME)

@Retention is a meta-annotation

Expresses the annotation retention policy. The constants of this type describe various policies for retaining annotations

Possible values:

  • RetentionPolicy.SOURCE: annotations are to be discarded by the compiler.
  • RetentionPolicy.CLASS (default): Annotations are to be recorded in the class file by the compiler but need not be retained by the VM at run time.
  • RetentionPolicy.RUNTIME: Annotations are to be recorded in the class file by the compiler and retained by the VM at run time, so they may be read reflectively.

@Target

@Target({ElementType.METHOD})
      // This annotation can only be applied to class methods.

The compiler reserves a set of special annotations (including @Deprecated, @Override and @SuppressWarnings) for syntactic purposes.