Java annotations

What are annotations?

Annotations are a form of metadata that provide some data to a program, but are not part of the program. Annotations do not provide operations directly to the code.

Function:

  • Tell the compiler to check for overrides (@Override), SuppressWarnings (@SuppressWarnings)
  • Compiler and deployment-time processing: Software tools can process annotations to generate code, XML files
  • Runtime processing: Some annotations can be checked at run time

basis

Format of annotations

@Entity

@Author( name = "Benjamin Franklin", date = "3/27/2003" )

Where it can be used:

Can be used on classes, methods, fields, or parameters

public enum ElementType {

/* Class, interface (including annotation type), or enum declaration /

TYPE,

/* Field declaration (includes enum constants) /

FIELD,

/* Method declaration /

METHOD,

/* Formal parameter declaration /

PARAMETER,

/* Constructor declaration /

CONSTRUCTOR,

/* Local variable declaration /

LOCAL_VARIABLE,

/* Annotation type declaration /

ANNOTATION_TYPE,

/* Package declaration /

PACKAGE,

/*Type parameter declaration/

TYPE_PARAMETER,

/* Use of a type/

TYPE_USE

}

In Java 8, annotations can also be used on type

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 { … }

Declare an annotation type

Used in lieu of comments

public class Generation3List extends Generation2List {



// Author: John Doe

// Date: 3/17/2002

// Current revision: 6

// Last modified: 4/12/2004

// By: Jane Doe

// Reviewers: Alice, Bill, Cindy



// class code goes here



}

‎ To add this same metadata with annotation tags, you first need to define an annotation type. The syntax is as follows:

Note: Only basic types are allowed in annotations, plus enumerations, annotations, and strings.

public @interface ClassPreamble { String author(); String date(); int currentRevision() default 1; String lastModified() default “N/A”; String lastModifiedBy() default “N/A”; // Using array String[] reviewers(); }

The definition of an annotation is a bit like an interface, but an annotation is also a form of an interface.

The element declaration of an annotation is a bit like the method of an interface; the element of an annotation can be set to default values. If you want it to appear in Javadoc, you need to add the @Document annotation

Predefined annotation types

Some annotations are already defined in the Java SE API. Some annotation types are used by the Java compiler, and some annotations are used on other annotations.

Is used in the Java language

@Deprecated

@Override

@SuppressWarnings

@SafeVarargs

@FunctionalInterface

Apply to other annotations

Annotations that apply to other annotations are called meta-annotations. Meta annotations are defined in the.java.lang.annotation.

The @Retention annotation is used to specify the period during which the annotation is stored

RetentionPolicy.source This means that annotations are only retained in the SOURCE code and will be ignored by the compiler

RetentionPolicy.class This means that annotations are retained until compile time, but ignored by the JVM

RetentionPolicy.Runtime This means that the annotations will be retained in the JVM, which means they can be used at RUNTIME.

@Documented displays the content of this annotation when you generate the Javadoc document

@target indicates where the annotation is used

  • ElementType.ANNOTATION_TYPECan be applied to annotation types
  • ElementType.CONSTRUCTORThis applies to constructors.
  • ElementType.FIELDCan be applied to fields or properties
  • ElementType.LOCAL_VARIABLECan be used on local variables.
  • ElementType.METHODYou can apply it to methods.
  • ElementType.PACKAGEIt can be on the package path.
  • ElementType.PARAMETERCan be applied to method parameters.
  • ElementType.TYPEClass that can be used.

@Inherited means that this annotation class can be Inherited from its parent class and can only be used for class declarations.

@repeatable was introduced in Java8, and annotations for this tag can be declared multiple times

Type Annotation and pluggable type system

Type annotations were created to support improved analysis of Java programs and are a way to ensure strong type checking. There is no framework for checking in the Java 8 release, but Java 8 allows us to write a framework for type checking that implements one or more modules that act as plug-ins to the Java compiler.

For example, if you want to ensure that certain arguments in your program are never null, and you want to avoid null-pointer exceptions, you can customize a plugin to check that. All you need to do is modify your code to add comments that indicate that certain variables can be NULL assigned. Like this

@Notnull String str;

When you compile the code, the compiler will print out a warning if it detects some potential problem. Allows you to modify code to avoid errors. When the code is corrected, this error will not appear in the program.

Repeat Annotations

Many times, we want to use an annotation multiple times on a declaration or type. In Java 8, repeated annotations provide the functionality we need.

For compatibility, duplicate annotations are stored in the container annotation container, which is automatically generated by the compiler. In order for the compiler to do this, a two-step declaration needs to be implemented in the code.

Step 1: Define a repeating annotation class

This Repeatable annotation class must be marked with Repeatable meta annotations. Here is a repeat annotation to define @schedule:

@repeatable (Schedules. Class) public @interface Schedule {String dayOfMonth() default “first”; String dayOfWeek() default “Mon”; int hour() default 12; }

The value of this meta-annotation (the value in parentheses) is the container annotation generated by the Java compiler that stores the class of the annotation. (That is, the value is the type of the container that holds the comments). In this case, the container annotation is of type Schedules, so the repeat annotation @schedule was stored in the @schedules annotation.

Step 2: Declare a container annotation type

The container annotation type must contain a value element whose type is an array. The component type must be the type of the repeating annotation. The declared Schedules container annotation type is as follows:

public @interface Schedules { Schedule[] value(); // an array of Schedule}

Retrieving a eving Annotation

There are several ways to get annotations in the reflection API. There are ways to get an annotation. For example,

[AnnotatedElement getAnnotation (Class)] if there is only an annotation in parentheses (value), it returns an intact annotations (value), if there are multiple annotation parentheses, also can get annotations to the container to get through to. In this way, the code can continue to run. Another is that the Java 8 new models, can be a one-time return multiple annotations, such as AnnotatedElement. GetAnnotations (Class < T >).

Resources: Java Lesson

  1. What is wrong with the following interface?

    public interface House {
        @Deprecated
        void open();
        void openFrontDoor();
        void openBackDoor();
    }
  2. Consider this implementation of the House interface, shown in Question 1.

    public class MyHouse implements House { public void open() {} public void openFrontDoor() {} public void openBackDoor() {}}