Java注解 Annotation

ref

Annotations, a form of metadata, provides data about a program that is not
part of the program itself. Annotations have no direct effect on the operation
of the code they annotate.

Annotations have a number of uses, among them:

  • Information for the compiler
  • Compile-time and deployment-time processing
  • Runtime processing

Format and Effect

@annotationName{field = val}

Declarations: declarations of classes, fields, methods, and other elements. When used on
declaration often appears, by convention on its own lines.

  • Class instance creation expression

new @Interned MyObject();

  • Type cast

myString = (@NonNull String) str;

  • implements clause

class UnmodifiableList<T> implements @Readonly List<@Readonly T> {...}

  • Thrown exception declaration
void monitorTemperature() throws 
@Critical TemperatureException{...}

Declaring an Annotation Type

Define the annotation type:

@interface ClassPreamble{
	String author();
	String date();
	int currentVersion() default 1;
	String lastModified(0 default "N/A";
	String lastModifiedBy() default "N/A";
	// Note use of array
    String [] reviewers();

Usage:

  @ClassPreamble (
  author = "Sonnet"
  date = "2021-06-09",
  currentVersion = 6,
  lastModified = "2021-06-10",
  reviewers = {"Alice", "Bob", "Caws"}
  )
  public class Generation3List extends Gereration2List{
	//code here
  }

Note: To make the information in @ClassPreamble appear in
Javadoc-generated documentation, you must annotate the @ClassPreamble definition with the @Documented annotation:

// import this to use @Documented
import java.lang.annotation.*;

@Documented
@interface ClassPreamble {

   // Annotation element definitions
}

Predefined Annotation Types

Defined in java.lang

  • @Deprecated Mark the element as deprecated and should no longer be used.

For method be marked as deprecated, it should also be documentated using Javadoc
@deprecated tag.

  // Javadoc comment follows
    /**
     * @deprecated
     * explanation of why it was deprecated
     */
    @Deprecated
    static void deprecatedMethod() { }
}

**Note: @deprecated in Javadoc while @Deprecated in annotation **

  • Override informs the compiler that the element is meant to overide an element
    declared in a superclass.

  • @SuppressWarnings annotation tells the compiler to suppress specific warnings that it would otherwise generate.(suppress 阻止,抑制)

   // use a deprecated method and tell 
   // compiler not to generate a warning
   @SuppressWarnings("deprecation")
    void useDeprecatedMethod() {
        // deprecation warning
        // - suppressed
        objectOne.deprecatedMethod();
    }
@SuppressWarnings({"unchecked", "deprecation"})
  • @SafeVarargs @SafeVarargs annotation, when applied to a method or constructor,
    asserts that the code does not perform potentially unsafe operations on its varargs parameter.
    When this annotation type is used, unchecked warnings relating to varargs usage are suppressed.

  • @FunctionalInterface @FunctionalInterface annotation, introduced in Java SE 8,
    indicates that the type declaration is intended to be a functional interface, as defined by the Java Language Specification.

Annotations That Apply to Other Annotations

Annotations that apply to other annotations are called meta-annotations. There are several meta-annotation types defined in java.lang.annotation.

  • @Retention @Retention annotation specifies how the marked annotation is stored:

  • RetentionPolicy.SOURCE – The marked annotation is retained only in the source level and is ignored by the compiler.

  • RetentionPolicy.CLASS – The marked annotation is retained by the compiler at compile time, but is ignored by the Java Virtual Machine (JVM).

  • RetentionPolicy.RUNTIME – The marked annotation is retained by the JVM so it can be used by the runtime environment.

  • @Documented @Documented annotation indicates that whenever the specified annotation
    is used those elements should be documented using the Javadoc tool.
    (By default, annotations are not included in Javadoc.) For more information, see the Javadoc tools page.

  • @Target @Target annotation marks another annotation to restrict what kind
    of Java elements the annotation can be applied to.
    A target annotation specifies one of the following element types as its value:

  • ElementType.ANNOTATION_TYPE can be applied to an annotation type.

  • ElementType.CONSTRUCTOR can be applied to a constructor.

  • ElementType.FIELD can be applied to a field or property.

  • ElementType.LOCAL_VARIABLE can be applied to a local variable.

  • ElementType.METHOD can be applied to a method-level annotation.

  • ElementType.PACKAGE can be applied to a package declaration.

  • ElementType.PARAMETER can be applied to the parameters of a method.

  • ElementType.TYPE can be applied to any element of a class.

  • @Inherited @Inherited annotation indicates that the annotation type can be
    inherited from the super class. (This is not true by default.) When the user
    queries the annotation type and the class has no annotation for this type,
    the class' superclass is queried for the annotation type. This annotation applies only to class declarations.

  • @Repeatable @Repeatable annotation, introduced in Java SE 8, indicates
    that the marked annotation can be applied more than once to the same declaration
    or type use. For more information, see Repeating Annotations.

Repeatable Annotations

There are some situations where you want to apply the same annotation to a
declaration or type use. As of the Java SE 8 release, repeating annotations enable you to do this.

  1. Declare a Repeatable Annotation Type
import java.lang.annotation.Repeatable;

@Repeatable(Schedules.class)
public @interface Schedule {
  String dayOfMonth() default "first";
  String dayOfWeek() default "Mon";
  int hour() default 12;
}
  1. Declare the Containing Annotation Type
public @interface Schedules {
    Schedule[] value();
}
原文地址:https://www.cnblogs.com/sonnet/p/15187513.html