Java @Retention

www.‮ual‬tturi.com
Java @Retention

In Java, the @Retention annotation specifies the retention policy for a particular annotation. The retention policy controls the duration for which the annotated element will be available to be accessed by reflection at runtime.

There are three possible values for the RetentionPolicy enumeration that can be specified with the @Retention annotation:

  • RetentionPolicy.SOURCE: The annotation will be retained only in the source code and will be discarded by the compiler. This is the default retention policy if no @Retention annotation is present.
  • RetentionPolicy.CLASS: The annotation will be retained by the compiler and included in the class file, but will not be available at runtime.
  • RetentionPolicy.RUNTIME: The annotation will be retained by the compiler and included in the class file, and will also be available at runtime through reflection.

Here is an example of how the @Retention annotation can be used:

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    String value();
}

In this example, the MyAnnotation annotation will be retained at runtime and can be accessed via reflection.

It is important to note that the @Retention annotation only applies to annotations and has no effect on other types of elements such as classes or methods.

Created Time:2017-11-01 22:29:45  Author:lautturi