Java - Annotations

java

https://dzone.com/articles/creating-custom-annotations-in-java
https://docs.oracle.com/javase/tutorial/java/annotations/predefined.html
https://docs.oracle.com/javase/tutorial/java/annotations/repeating.html
https://docs.oracle.com/javase/tutorial/java/annotations/type_annotations.html

The annotation can include elements, which can be named or unnamed, and there are values for those elements.

@Author(
   name = "Benjamin Franklin",
   date = "3/27/2003"
)
class MyClass() { ... }
@SuppressWarnings(value = "unchecked")
void myMethod() { ... }

If there is just one element named value, then the name can be omitted, as in:

@SuppressWarnings("unchecked")
void myMethod() { ... }

If the annotation has no elements, then the parentheses can be omitted, as shown in the previous @Override example.

It is also possible to use multiple annotations on the same declaration:

@Author(name = "Jane Doe")
@EBook
class MyClass { ... }

If the annotations have the same type, then this is called a repeating annotation:

@Author(name = "Jane Doe")
@Author(name = "John Smith")
class MyClass { ... }

Repeating annotations are supported as of the Java SE 8 release. See https://docs.oracle.com/javase/tutorial/java/annotations/repeating.html

The annotation type can be one of the types that are defined in the java.lang or java.lang.annotation packages of the Java SE API. In the previous examples, Override and SuppressWarnings are predefined Java annotations. It is also possible to define your own annotation type. The Author and Ebook annotations in the previous example are custom annotation types.

What is the definition of meta-annotation?

Annotations that apply to other annotations are called meta-annotations.

What are available predefined annotations?

  1. @Deprecated: indicates that the marked element is deprecated and should no longer be used. The compiler generates a warning whenever a program uses a method, class, or field with the @Deprecated annotation. When an element is deprecated, it should also be documented using the Javadoc @deprecated tag. The use of the at sign (@) in both Javadoc comments and in annotations is not coincidental: they are related conceptually. Also, note that the Javadoc tag starts with a lowercase d and the annotation starts with an uppercase D.
  2. @Override: informs the compiler that the element is meant to override an element declared in a superclass. While it is not required to use this annotation when overriding a method, it helps to prevent errors. If a method marked with @Override fails to correctly override a method in one of its superclasses, the compiler generates an error.
  3. @SuppressWarnings: tells the compiler to suppress specific warnings that it would otherwise generate. In the following example, a deprecated method is used, and the compiler usually generates a warning. In this case, however, the annotation causes the warning to be suppressed. Every compiler warning belongs to a category. The Java Language Specification lists two categories: deprecation and unchecked. The unchecked warning can occur when interfacing with legacy code written before the advent of generics.
  4. @SafeVarargs: 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.
  5. @FunctionalInterface: introduced in Java SE 8, indicates that the type declaration is intended to be a functional interface.
  6. @Retention: specifies how the marked annotation is stored:
    1. RetentionPolicy.SOURCE – The marked annotation is retained only in the source level and is ignored by the compiler.
    2. RetentionPolicy.CLASS – The marked annotation is retained by the compiler at compile time, but is ignored by the Java Virtual Machine (JVM).
    3. RetentionPolicy.RUNTIME – The marked annotation is retained by the JVM so it can be used by the runtime environment.
  7. @Documented: 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.)
  8. @Target: 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:
    1. ElementType.ANNOTATION_TYPE can be applied to an annotation type.
    2. ElementType.CONSTRUCTOR can be applied to a constructor.
    3. ElementType.FIELD can be applied to a field or property.
    4. ElementType.LOCAL_VARIABLE can be applied to a local variable.
    5. ElementType.METHOD can be applied to a method-level annotation.
    6. ElementType.PACKAGE can be applied to a package declaration.
    7. ElementType.PARAMETER can be applied to the parameters of a method.
    8. ElementType.TYPE can be applied to any element of a class.
  9. @Inherited: 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.
  10. @Repeatable: 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.
// mark method as a superclass method that has been overridden
@Override
void mySuperMethod() { ... }

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

// use a deprecated method and tell compiler not to generate a warning
@SuppressWarnings("deprecation")
void useDeprecatedMethod() {
    // deprecation warning
    // - suppressed
    objectOne.deprecatedMethod();
}

See https://docs.oracle.com/javase/tutorial/java/annotations/predefined.html

How can we suppress warning for multiple categories?

Every compiler warning belongs to a category. The Java Language Specification lists two categories: deprecation and unchecked. The unchecked warning can occur when interfacing with legacy code written before the advent of generics. To suppress multiple categories of warnings, use the following syntax:

@SuppressWarnings({"unchecked", "deprecation"})

Can we define our own annotations?

Yes.

How can we define our own annotations?

I NEED TO COMPLETE THIS.

Where can we use annotations?

Annotations can be applied to declarations: declarations of classes, fields, methods, and other program elements. When used on a declaration, each annotation often appears, by convention, on its own line.

As of the Java SE 8 release, annotations can also be applied to the use of types. Here are some examples:

// 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 { ... }

This form of annotation is called a type annotation.

How can we declare our own annotation type?

Many annotations replace comments in code. Suppose that your company traditionally starts the body of every class with comments providing important information, such as:

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 the same metadata with an annotation, you must first define the annotation type. The syntax for doing this is:

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

Notice that the above code use the keyword interface, but with the @ sign in-front of it. The annotation type definition looks similar to an interface definition where the keyword interface is preceded by the at sign. Annotation types are a form of interface. The body of the previous annotation definition contains other annotation type element declarations, which look a lot like methods, (and perhaps they are actually callable method in some way). Note that they can define optional default values. After the annotation type is defined, you can use annotations of that type, with the values filled in, like this:

@ClassPreamble (
   author = "John Doe",
   date = "3/17/2002",
   currentRevision = 6,
   lastModified = "4/12/2004",
   lastModifiedBy = "Jane Doe",
   // Note array notation
   reviewers = {"Alice", "Bob", "Cindy"}
)
public class Generation3List extends Generation2List {
    // class code goes here
}

Notice that the annotation appears outside of the class definition, and just immediately before the class definition. 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
}

What is the definition of 'annotation'?

Annotation is a form of metadata. It 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:

  1. Information for the compiler — Annotations can be used by the compiler to detect errors or suppress warnings.
  2. Compile-time and deployment-time processing — Software tools can process annotation information to generate code, XML files, and so forth.
  3. Runtime processing — Some annotations are available to be examined at runtime.

What is the format of an annotation?

In its simplest form, an annotation looks like the following:

@Entity

where Entity can be something like Override to indicate that the method is overridden:

@Override
void mySuperMethod() { ... }

The at sign character (@) indicates to the compiler that what follows is an annotation.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License