Annotation (Java)

from Wikipedia, the free encyclopedia

In connection with the Java programming language, annotation is a language element that allows metadata to be incorporated into the source text . This element was defined in JSR 175 and introduced with version Java 5.0.

Annotations begin with an @ sign. This is followed by her name. A comma-separated parameter list, which is enclosed in round brackets, can optionally follow. For example, the annotation in the following excerpt from the source code marks class A as deprecated :

@Deprecated
public class A {}

An Annotation Processor is a compiler plug-in that can evaluate annotations during compilation in order to suppress or trigger warnings and error messages or to generate additional source code or other files. However, he cannot change annotated code. Annotations for which this is intended can also be evaluated at runtime using reflection .

Annotations are used, among other things, in the Java EE environment to add information to classes that had to be stored in separate files before Java 5. Prominent examples are home and local interfaces as well as deployment descriptors.

A previous technique for embedding metadata in Java source code is the use of special Javadoc comments. These were evaluated with the help of so-called doclets . A widely used tool for this method is XDoclet . This technique can still be used after the introduction of the annotations.

Predefined annotation types

In Java SE 5.0 are seven predefined annotation types available, in the packages ( package ) java.langor java.lang.annotationlie. In contrast to most annotations, they are all evaluated by the compiler. Programmers can create more.

Annotation description
java.langThere are annotations in the package .
@Deprecated This can be used to mark classes, attributes or methods that should no longer be used. The compiler then issues a warning if an element marked in this way is used.

It is also advisable to add a Javadoc comment that shows how the corresponding element should be replaced. The following example shows this:

/**
 * @deprecated  Die Klasse A wurde mit Version 10.3 durch die Klasse ANeu ersetzt.
 */
@Deprecated
public class A {}
@Override This type can be used to identify a method that overwrites the method of its superclass. The compiler then ensures that the superclass contains this method and returns an error if it does not.

Example:

public class A {
    public void eineMethode() {}
}
 
public class B extends A {
    @Override
    public void eineMethode() {}
}
@SuppressWarnings When using this type of annotation, the compiler suppresses certain warnings. An array with strings containing the warnings to be suppressed is transferred to the annotation.

The following example instructs the compiler to suppress the deprecated warning for the ADeprecatedClass class:

public class A {
    @SuppressWarnings({"deprecation"})
    public void eineMethode() {
        EineDeprecatedKlasse b = new EineDeprecatedKlasse();
    }
}
@SafeVarargs This annotation ensures that the varargs parameters with generics are not replaced with an unsuitable generics type at runtime. No warning is then displayed when the method or constructor is called. The annotation was introduced with Java 7. Up to Java 6 you could document the trust in the called code when calling with an @SuppressWarnings annotation, from Java 7 the method can declare itself as trustworthy.
In the package java.lang.annotation- these are only used to define annotations.
@Documented This annotation type is used as meta annotation: An annotation of this type specifies for a newly created annotation type that Javadoc takes it into account when generating the documentation.
@Inherited This type of annotation is used when programming an annotation. This can be used to specify that this is inherited together with a class. If this annotation is then used, for example, for a certain class, it also applies to all classes that inherit from it.
@Retention This type is used when programming an annotation. It indicates when it can be accessed by itself. There are three possible values ​​for an annotation of this type, which are listed in the enumeration java.lang.annotation.RetentionPolicy :
CLASS
The annotation is compiled with the class and is therefore available in the .class file. However, it cannot be read out while an application is running. This is the default.
RUNTIME
The annotation can be read out during the runtime of an application using the reflection mechanism .
SOURCE
The annotation is removed from the source code before compilation. Accordingly, it is not available when a program is running.
@Target This type of annotation is used when programming an annotation. This defines which elements of a program it can be applied to. The possible values ​​for an annotation of this type are listed in the enumeration java.lang.annotation.ElementType.
TYPE
The annotation can only be applied to classes, interfaces or enumerations.
FIELD
The annotation can only be applied to fields.
METHOD
The annotation can only be applied to methods. Constructors are excluded.
PARAMETER
The annotation can only be applied to parameters of methods and constructors.
CONSTRUCTOR
The annotation can only be applied to constructors.
LOCAL_VARIABLE
The annotation can only be applied to local variables.
ANNOTATION_TYPE
The annotation can only be applied to annotations.
PACKAGE
The annotation can only be applied to packages.

Definition of your own annotations

Annotations are special interfaces; Therefore, according to the convention, their names are written with capital letters. In their agreement there is interfacethe sign @. They implicitly extend the interface java.lang.annotation.Annotation. They must not extend any other interfaces (i.e. extendsare prohibited) and are not generic. Their methods are parameterless and non-generic. Only the following types are permitted as result types (return type):

  • primitive types
  • Enumeration types ( enum)
  • Annotation types
  • String
  • Class
  • Fields (arrays) from these types

They also don't throw exceptions and aren't allowed to use recursion.

Many annotations do not contain methods. An example would be:

@interface Vorlaeufig { }

Other annotations contain methods (as is usual for interfaces), but only with the result types listed above. By convention, if an annotation contains only one method, its name is value:

@interface Test {
	boolean value(); // true solange nicht freigegeben
}

or

@interface Autoren {
	String[] value(); // Namen der Autoren
}

or

@interface Kunden {
	Person[] value();
}

where person enummust be defined as enumeration type ( ) or annotation, e.g. B .:

@interface Person {
	String name();
	int alter();
}

When agreeing on annotations, the standard annotations from the package are often java.lang.annotationused. In particular, it should be @Retentionspecified how long the annotation should be kept: only in the source code ( SOURCE), in the saved class file ( CLASS) or also in the loaded class ( RUNTIME). @Targetdescribes for which program elements the annotation can be used. For example, all annotation agreements are in the package java.lang.annotationwith the annotations

@Documented
@Retention(value=RUNTIME)
@Target(value=ANNOTATION_TYPE)

Mistake. This means that they are all evaluated by javadoc, loaded in the bytecode and can thus be evaluated at runtime; in addition, they may only be used for annotation types.

Use of your own annotations

An annotation without methods, such as @Vorlaeufig, can e.g. B. be placed in front of a class:

@Vorlaeufig
class Klasse {
	void methode();
}

An annotation with only one method with the name valuemust be given a constant value of the result type of this method in brackets:

@Test(true)
public void methode() { ... }

If the result type is an array, an array literal should be used:

@Autoren({"Solymosi", "Grude"})
String buch = "Algorithmen und Datenstrukturen mit Java"

If the array does not contain any elements, must also be ({})specified. However, if the array contains only one element, the curly braces can be omitted:

@Autoren("Solymosi")
String anderesBuch = "Programmieren in Scala"

An annotation with several methods must be assigned a constant value in brackets to each of its methods:

@Person(name = "Andreas Solymosi", alter = 56)
Konto konto = new Konto();

The option of specifying the value by name is also available for annotations with a method (however, it is superfluous, at most for readability):

@Test(value = true)

A complex (nested) annotation must be applied nested:

@Kunden(@Person(name = "Andreas Solymosi", alter = 56))
class Unternehmen {  }

Standard values ​​can be defined for the methods in the annotation agreement; then the corresponding value can be omitted when used. Since annotations are interfaces, they can be marked with annotations themselves:

@Autoren("Solymosi")
public @interface Test {
	boolean wert() default false; // muss nicht unbedingt wert heißen
}

Evaluation of annotations

If the annotations are loaded with the bytecode of the class, they can be evaluated using reflection. For example, you can determine whether an annotation has been specified or not:

boolean vorlaeufig = Klasse.class.isAnnotationPresent(Vorlaeufig.class);

When you have determined that the annotation is there, you can also read its value, e.g. B. whether the method is still in the test state or not:

boolean imTestzustand = Klasse.class.getMethod("methode", new Class[]{}).getAnnotation(Test.class).value();

If the annotation does not exist, getAnnotation()the exception is NullPointerExceptionraised. Its elements must be selected individually from a complex annotation:

Person kunden = Unternehmen.class.getAnnotation(Kunden.class).value()[0];

Annotation of packages

The Java Language Specification also allows packages to be annotated, for example to provide documentation for a package. A maximum of one packagedeclaration may be annotated per package . If a package is to receive annotations, the Java Language Specification recommends creating a separate file package-info.javain the directory of this package. This file then contains the packagedeclaration with the annotations.

Web links