[Translation] Java annotation tutorial

Source: Internet
Author: User

[Translation] Java annotation tutorial

Annotation

AnnotationThe metadata format provides data about the program, which is not part of the program. Annotations do not directly affect the operations of the codes they annotate.

Annotations have multiple purposes, including:
-Provide information to the compiler -- the compiler uses annotation to check for errors or ignore warnings
-Processing during compilation and deployment-software tools can process annotation information to generate code and XML files.
-Runtime processing-some annotations are reviewed at runtime

This course explains where annotations can be used, how annotations can be used, and what predefined annotation types are available on the Java platform.

Basic annotation format

Simple format. The annotation looks like this:

@Entity

The at sign (@) indicates that the compiler is followed by an annotation. In the following example, the annotation name is Override:

@Overridevode mySuperMethod() {...}

Annotations can containElementThe element can be named or not, and the element can be assigned a value:

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

Or

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

If there is no element in the annotation, parentheses can be omitted, just like @ Override.

Multiple annotations can be used for the declaration:

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

If the annotation has the same type, this is called repeated annotation:

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

With the release of Java SE 8, repeated annotations are supported. For more information, see repeated annotations.

The annotation type can be one of the types defined in the Java. lang or java. lang. annotation package in the java se api. In the previous example, Override and SuppressWarnings are pre-defined Java annotations. You can also customize the annotation type. Author and Ebook annotations in annotations are custom annotation types.

Where is the annotation used?

Annotations can be used to declare classes, fields, methods, and other program elements. When used for declaration, each annotation is a single row by convention.

With the release of Java SE 8, annotations can also be applied to types.Use. Example:
-Expression for creating a class instance:
new @Interned MyObject();
-Forced conversion:
myString = (@NonNull String) str;
-Implementation interface:
class UnmodifiableList implements @Readonly List<@Readonly T> { ... }
-Throw an exception declaration:
void monitorTemperature() throws @Critical TemperatureException { ... }
This type of annotation is called a type annotation. For more details, see the type annotation and pluggable type system.

Declaration Annotation

Many annotations replace comments in the code.

Suppose a software group usually adds important information comments at the beginning of each class file:

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 using annotations, you must first defineAnnotation type. Syntax:

@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();}

Annotation type definition looks like interface definition, keywordInterfaceAdd the at sign (@) (@ = AT for the annotation type ). Annotation type isInterfaceThe interface will be explained in the subsequent sections. Now, you do not need to understand the interface.

The subject defined in the preceding annotation containsAnnotation type elementStatement, which looks like a method. Note: You can define optional default values.

After the annotation type is set, you can use this annotation and fill in some values, such:

@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}
Predefined annotation type

Java se api predefines a set of annotation types. Some annotations are used in the Java compiler and some are applicable to other annotations.

Annotation type used in Java

Java. lang pre-defined annotation types include @ Deprecated, @ Override, and @ SuppressWarnings.

@ Dreprecated@ Dreprecated annotation indicates that the marked element hasDiscardAnd will not be used in the future. When a program uses a method, class, or domain with @ Deprecated annotation, the compiler generates a warning. When an element is discarded, the @ deprecated tag of Javadoc should be used in the document, as shown in the following example. It is no coincidence that the at sign (@) is used in Javadoc comments and annotations: they are conceptually related. In addition, Javadoc is activated with lowercase d, and the annotation starts with uppercase D.

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

@ Override@ Override annotation notifies the compiler that this element is included in the element declared in the superclass. The rewriting method will be discussed in the interface and inheritance.

// mark method as a superclass method// that has been overridden@Override int overriddenMethod() { }

However, using this annotation to rewrite the method is not necessary, and it helps prevent errors. If the method marked with @ Override cannot correctly Override the method in the superclass, the compiler will generate an error.

@ SuppressWarnings@ SuppressWarnings annotation tells the compiler to ignore the specified warning. In the following example, a discard method is used, and the compiler usually generates a warning. In this case, the warning is ignored when this annotation is used.

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

The compiler classifies warnings. Java language specifications are divided into two types: obsolete and unselected. The interface that contains the old code before the generic type generates an unselected warning. To ignore multiple types of warnings, use the following syntax:

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

@ SafeVarargs@ SafeVarargs annotation, which is applicable to methods or constructor and asserted that the variable parameters in the specified code are not executed for potential insecure operations. When this annotation type is used, unselected warnings related to variable parameters are ignored.

@ FunctionalInterface@ FunctionalInterface annotation, introduced in Java SE 8, indicates that this type declaration represents the function interface defined by the Java language specification.

Annotations applied to other annotations

Annotations applied to other annotations are calledMeta Annotation, Java. lang. annotation defines some meta annotations.

@ Retention@ Resolve ention annotation specifies the storage method of the tag annotation:

RetentionPolicy. SOURCE -- Annotation is only held at the code level and ignored by the compiler. RetentionPolicy. CLASS -- Mark annotation held by the compiler during compilation and ignored by the Java Virtual Machine (JVM. RetentionPolicy. RUNTIME -- Annotation held by JVM, which can be used in the RUNTIME environment.

@ Brief ented@ Brief ented annotation indicates that the elements using the specified annotation should be Documented using the Javadoc tool. (By default, annotations are not included in Javadoc .) For more information, see the Javadoc tool page.

@ Target@ Target annotation marks other annotations to limit the Java elements that the Target annotation can apply. The target annotation specifies the following element as its value:
-ElementType. ANNOTATION_TYPE can be applied to annotation types.
-ElementType. CONSTRUCTOR can be applied to constructors.
-ElementType. FIELD can be applied to fields or attributes.
-ElementType. LOCAL_VARIABLE can be applied to local variables.
-ElementType. METHOD can be used for METHOD-level annotations.
-ElementType. PACKAGE can be used for PACKAGE Annotation
-ElementType. PARAMETE can be used for method parameters.
-ElementType. TYPE can be applied to any element of the class.

@ Inherited@ Inherited annotation indicates that the annotation type can be Inherited from the superclass. (The default value is false .) When you query the annotation type, which is not marked with this annotation type, the annotation type of the parent class will be queried. This annotation applies only to class declarations.

@ Repeatable@ Repeatable annotation, introduced in Java SE 8, indicates that the annotation marked can be reused with the same declaration or type. For more information, see repeated annotations.

Type annotation and pluggable Type System

Before Java SE 8 is released, annotations can only be used for declaration. With the release of Java SE 8, annotations also apply to anyType usage. This means that the annotation can be applied to any type of use. Types can be used in the following ways: Class instantiation, creation expression (new), forced conversion, interface implementation, and exception throw. This form of annotation is called a type annotation, which provides some chestnuts.

The Type annotation is introduced to support the analysis of Java programs that ensure strong type checks. Java SE 8 does not provide a type check framework, but it allows writing (or downloading) the type check framework, which is used as one or more pluggable modules in combination with the Java compiler.

For example, you want to ensure that a special variable in the program is never set to null; you want to avoid NullPointerException. You can write a custom insert module to check it. You can modify the code to annotate this special variable, indicating that it will never be assigned null. The variable declaration may be like this:

@NonNull String str;

During code compilation, the command line includes the NonNull module. If the compiler detects potential problems, it will print a warning to remind you to modify the code to avoid errors. After all warnings are modified, special errors will not occur during program execution.

You can use multiple types of check modules. Each module checks for one type of error. In this way, you can build based on the Java type system, and add the specified type of check whenever and wherever necessary.

With the wise use of annotations and the existence of pluggable type checks, the code quality is improved and errors are reduced.

In many cases, the write type check module is not required. Third-party tools have been implemented. For example, you can use the Health Check framework created by the University of Washington. This framework includes the NonNull module, the regular expression module, and the mutex lock module. For more information, refer to the reviewer's framework.

Repeated Annotation

Sometimes you need to use the same annotation for the declaration or type. With the release of Java SE 8,Repeated AnnotationThis requirement can be listed.

For example, the Code uses the timer service to execute specific methods between specified or fixed intervals, similar to the cron service of UNIX systems. Now you want to add a timer to execute a method, doPeriodicCleanup, which goes to bed every day and every Friday eleven o'clock P.M. To start the timer, create a @ Schedule annotation and use the doPeriodicCleanup method twice. Specify the last day of each month for the first time and eleven o'clock P.M. for the second time on Friday, as shown in the following code:

@Schedule(dayOfMonth="last")@Schedule(dayOfWeek="Fri", hour="23")public void doPeriodicCleanup() { ... }

The preceding example shows how to add annotations. You can reuse annotations in any standard annotations. For example, there is a class that handles unauthenticated access exceptions. Annotation of this class, one @ Alert is used for the manager, and the other is used for the Administrator:

@Alert(role="Manager")@Alert(role="Administrator")public class UnauthorizedAccessException extends SecurityException { ... }

For compatibility reasons, repeated annotations are stored inInclude AnnotationContains annotations by Java
Compiler generation. In order for the compiler to do this, two declarations are required in the code.

* Step 1: declare a repeated annotation type *

The annotation type must be marked with @ Repeatable meta annotation. The following example defines the @ Schedule repeated 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;}

@ Repeatable the value of the metadatable annotation, which is in parentheses and contains the annotation type. The Java compiler generates the annotation for storing repeated annotations. In this example, the annotation type is Schedules, so the repeated @ Schedule annotation will be stored in the @ Schedules annotation.

A compile-time error is generated when you use a non-declarative annotation to declare it.

Step 2: declare annotation types

A value element of the array type must be specified for the annotation type. Components of the array type must be repeated annotation types. The Schedules declaration containing annotation types is as follows:

public @interface Schedules {  Schedule[] value();}
Search Annotation

There are some methods in the reflection API that can be used to retrieve annotations. The behavior of these methods is to return a single annotation, such as AnnotatedElement. getAnnotationByType (Class). If the request type is found, it returns only a single annotation. If multiple annotations of the Request type exist, you can obtain their containing annotations first. Only the old code can be used. Other methods added in Java SE 8 include annotations, and multiple annotations are returned at a time, such as AnnotatedElement. getAnnotations (Class ). See all available method information in the AnnotatedElement class specification.

Design Considerations

When designing annotation types, you must consider the base of annotation types. Currently, annotations can be used once or multiple times. If the annotation type is marked as @ Repeatable. You can also use the @ Target meta annotation to display the usage of annotation types. For example, create a repeatable annotation that is only used in methods and fields. It is important to carefully design annotation types to ensure that programmers find them flexible and powerful when using annotations.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.