Understanding of Java Basics Annotation

Source: Internet
Author: User
Tags constant definition

Understanding of Java Basics Annotation

Starting with JDK version 1.5, the Java language provides a common Annotation feature that allows developers to define and use their own Annotation types. The Annotation feature includes syntax for defining Annotation types, syntax for annotating declarative expressions, reading Annotation's api,annotation in class files, and Annotation processing tools (APT).

Annotation does not directly affect the syntax of the program, but it provides data or information outside of the program, affecting how the tool or class library processes or invokes the program, ultimately affecting the behavior of the program at runtime.

Annotation features are now widely used in the development of various Java-based application systems. The Java API itself pre-defines a series of Annotation types, such as @Deprecated, @Override, @SuppressWarnings, and so on. Various Annotation, such as @Required in Spring, @Autowired, @Aspect, @Pointcut and so on, are often used in popular frameworks.

For Java developers, it is likely that the code and software quality has been improved by using Annotation. Taking @Override tags as an example, in large projects with complex inheritance structures, it is difficult for a developer to visually determine which subclass of a particular implementation is called at run time, for one of the methods of the parent class. And once the developer changes the method name or its arguments of the parent class, ignoring the same modifications to the subclass, the overridden methods in the subclasses are no longer called, causing the system to render the expected behavior or result. By introducing the @Override tag, the Java compiler will prompt the developer to synchronize the rewriting methods in all related subclasses to avoid this problem when compiling the relevant code.

To better help developers improve the quality and readability of their code and automate the accuracy of code analysis, Java 8 introduces two important changes to Annotation: Type Annotation and repeating Annotation.

Back to top of page

Java 8 Annotation new features first experience feature one: Type Annotation

In versions prior to Java 8, it was permissible to use Annotation only before declarative. In Java version 8, Annotation can be used wherever type is used, such as when initializing an object (new), when an object type is converted, when using a implements expression, or when using a throws expression.

Listing 1. Type Annotation Use Example
                    string myString = new @NotNull string () when initializing the object;          Object type conversion when          myString = (@NonNull String) str;          When using implements expressions,          class Mylist<t> implements @ReadOnly list< @ReadOnly t>{                              ...           }           Use throws expression when public           void Validatevalues () throws @Critical validationfailedexception{                              ...            }

The method of defining a Type Annotation is similar to a normal Annotation, which requires only specifying the Target of Elementtype.type_parameter or elementtype.type_use, or specifying the two Ta Rget.

Listing 2. Defining the Type Annotation example
          @Target ({elementtype.type_parameter, elementtype.type_use})          public  @interface myannotation {          }

Elementtype.type_parameter indicates that the Annotation can be used before the type's declarative, and Elementtype.type_use indicates that the Annotation can be used in all places where the type is used (for example, generics, type conversion, etc.)

Similar to Annotation before Java 8, Type Annotation can also be accessed by setting the Retention to remain in the class file (Retentionpolicy.class) or run-time (Retention Policy.runtime). However, unlike before, type Annotation has two new features: Annotation on local variables can be persisted in the class file, and generic types can be preserved and even accessed at run time.

Although Type Annotation can remain in the class file, it does not alter the behavior of the program code itself. For example, by adding Annotation to a method, the result returned by calling this method is the same as when the Annotation is not added.

Java 8 introduces the type Annotation, allowing developers to use Annotation in more places, allowing them to analyze the code more comprehensively and perform more type checking.

Feature two: repeating Annotation

In practice, there may be situations where you need to add the same Annotation (with different property values) to the same declarative or type.

For example, in addition to the administrator in the system, you have added the privilege of Super Administrator, and for some specific methods that can only be called by these two roles, you can use repeating Annotation.

Listing 3. Repeating Annotation Use example-1
          @Access (role= "Superadministrator")           @Access (role= "Administrator") public           void Docheck () {                         ...           }

The above example uses Annotation for methods, and developers can use repeating Annotation in other places depending on the specific needs of the product. For example, a class specifically provides administrator-related functionality that can be labeled directly on this class with the same Annotation.

Listing 4. Repeating Annotation Use example-2
          @Access (role= "Superadministrator")          @Access (role= "Administrator") Public          class adminservices{          }

Previous versions of the JDK do not allow developers to raise the same Annotation before the same declaration, even if the value of the property is different, and the code will prompt for errors during the compilation process. While Java 8 removes this limitation, developers can use repeating Annotation in all places where Annotation can be used, depending on the actual needs of their systems.

Due to compatibility, repeating Annotation is not the default feature for all newly defined Annotation, and requires the developer to determine whether the newly defined Annotation can be repeated according to their needs. The Java compiler automatically stores the repeating Annotation in the specified Container Annotation. To trigger the compiler to do this, the developer needs to define the following:

First, add @Repeatable tags before the Annotation that require repeating labeling features, as shown in the following example:

Listing 5. Defining repeating Annotation Examples
          @Repeatable (accesscontainer.class) public          @interface Access {                  String role ();          }

The value in parentheses after the @Repeatable tag is the type of the specified Container Annotation. In this example, the type of Container Annotation is the Accesscontainer,java compiler will save the duplicate Access object in Accesscontainer.

The value method that returns the array type must be defined in Accesscontainer. The type of the element in the array must be the corresponding repeating Annotation type. Specific examples are as follows:

Listing 6. Defining Container Annotation Examples
          Public @interface Accesscontainer {                 access[] value ();          }

The Annotation of annotations can be obtained through the reflection mechanism of Java. One way is to get Container Annotation first through the Getannotationbytype (class<t>) of the Annotatedelement interface, and then through the Container Annotation The value method obtains repeating Annotation. Another way is to return repeating Annotation at once using the Getannotations (class<t>) method of the Annotatedelement interface.

Repeating Annotation allows developers to add the same type of annotations to the same declarative or type based on specific requirements, thus increasing the flexibility and readability of the code.

Back to top of page

Code analysis in conjunction with the Checker Framework

Java 8 introduces new features of Annotation to support more comprehensive and in-depth analysis and validation of Java program code. Java 8, however, does not provide a validation framework for Annotation, and developers can choose from a number of third-party tools such as Checker framework, FindBugs, Eclipse, IntelliJ and other open source tools, and a number of other business analysis tools. These tools can be used in the IDE, maven/ant or the continuous integration platform.

The Checker Framework has the best compatibility with Java 8 compared to other open source tools, including support for Annotation in annotations. It itself has built-in validation classes for a range of common error types, such as null pointers, string format mismatches, unit of measure mismatches, security vulnerabilities, concurrency errors, and so on. The validation type can also be customized by the developer. In this article, you choose to use the Checker Framework for Annotation-based analysis and validation of your code.

Installing and configuring the Checker Framework
    1. Download the compressed package from the official site;
    2. Unzip the package and create a folder named Checker-framework;
    3. Configuration can be configured in the integrated development environment, the compilation tool, or the command line, as described in the official site.

If developers develop with an eclipse version that supports Java 8, such as 4.4.0, you can install the Checker Framework plug-in directly in Eclipse. The steps are as follows:

    1. Open Eclipse, select menu: Help, install new software;
    2. Click Add;
    3. The input name is Checker Framework and the address is http://types.cs.washington.edu/checker-framework/eclipse;
    4. Click Next until the end of the installation;
    5. Install complete Select Restart Eclipse.
Using the built-in check class

The Checker Framework provides a series of built-in validation classes, as follows:

Table 1. Checker Framework built-in check class
name function
Nullness Checker Detects and avoids system null pointer exceptions.
Javari Checker Detects and avoids the value of a read-only object being modified.
interning Checker Ensure that the reference comparison operator "= =" is used correctly, that is, "= =" is not used where the Equals () method should have been used.
Fenum Checker The full name is Fake enum Checker, which is used to ensure that the correct Fake enum constants are used.
Fake enum: That is, an int or String constant definition used instead of an enum, for example public static final @Fenum("A") int ACONST1 = 1 ;.
Format String Checker Detects and avoids using malformed strings in a formatted method such as System.out.printf () or String.Format ().
Linear Checker Ensure that the linear type system avoids the use of aliases, that is, an object can only have one reference at a time.
Lock Checker Detects and guarantees that the thread holds the appropriate lock when accessing the object or method being labeled.
Regex Checker Detects and guarantees that a String conforms to a regular expression.
Tainting Checker Detects if the data source parameter is potentially dirty.
i18n Checker Detects whether internationalization in the code is used correctly, that is, whether the string or object corresponds to a key in the Internationalized file or is consistent with the selected locale.

In the case of Nullness Checker, to parse the code using the Checker Framework, first label the corresponding Annotation on the object or method in the code that requires a short pointer check, as in the following example:

Listing 7. Nullness Checker Example-1
          Class Nullnessexample {             @Nullable Object O1;             @NonNull Object O2;             @EnsuresNonNullIf (expression= "Getcomponenttype ()", result=true) public              native Boolean IsArray ();              Public native @Nullable class<?> getcomponenttype ();           }

To perform the corresponding check plug-in, you only need to add the-processor plugin_class parameter when you compile normally with Javac. Specific examples are as follows:

Listing 8. Nullness Checker Example-2
Javac-processor Org.checkerframework.checker.nullness.NullnessChecker              Nullnessexample.java

Using the Checker framework plug-in in Eclipse, you can select the right-click option for the class or project you want to check directly, Checker Framework, Run built-in Checker, nullness Ch Ecker

Once the compilation is complete, you can find the appropriate prompt in the log. For example:

Listing 9. Nullness Checker Log
          Description:dereference of possibly-null reference O1          Resource:NullnessExample.java          Path:/mysamples/src/ Checkerframework/samples          location:26          type:checker Framework problem

This information allows developers to quickly and accurately locate potential flaws in the code, thus avoiding exceptions when the program runs.

Back to top of page

Annotation Verifying usage scenarios

Type Annotation provides more possibilities for checking in Java programs, however, it is more suitable for general format checks related to computer science than for business-side validation. For example, null pointer checks, numeric range checks, string format checksums, etc., can be easily verified by using the type Annotation combined with a third-party validation tool, such as the Checker Framework, to prevent the program from running with such errors or exceptions.

However, some specific business logic aspects of the checksum may not be suitable for implementation through Type Annotation. For example, when doing a transfer transaction, you need to check the user's rights and account balance, such as the need to deal with a variety of business data, it is difficult to pass the general verification framework to perform the verification.

Back to top of page

Conclusion

In Java 8, Annotation is well-extended and can be used wherever Type is used, not just before declarative. Annotation itself does not alter the running behavior of the program, but by using third-party tools such as the Checker Framework, developers can use Annotation to automate the detection of potential defects in the program, improve software quality, avoid duplication of development, Improve development efficiency.

Understanding of Java Basics Annotation

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.