A brief analysis of type annotation in Java8 _java

Source: Internet
Author: User

Note As you all know, starting from Java5 to join this feature, the development has now been everywhere, in many frameworks have been widely used to simplify the configuration in the program. What exactly is the controversial type annotation? Complex or convenient?

One, what is type annotation

Before Java 8, annotations could only be used where they were declared, such as classes, methods, attributes, and Java 8, where annotations can be applied anywhere, such as:

To create a class instance

Copy Code code as follows:
New @Interned MyObject ();

Type mappings
Copy Code code as follows:
myString = (@NonNull String) str;

In the Implements statement
Copy Code code as follows:
Class Unmodifiablelist<t> implements @Readonly list< @Readonly t> {...}

Throw Exception statement
Copy Code code as follows:
void Monitortemperature () throws @Critical temperatureexception {...}

Note that type annotations are syntax rather than semantics and do not affect Java compile time, load time, and run-time time, that is, when compiled into a class file, it does not contain type annotations.

Second, the role of type annotation

First look at the following code:

Copy Code code as follows:

Collections.emptylist (). Add ("one");
int I=integer.parseint ("Hello");
System.Console (). ReadLine ();

The above code compiled is passed, but the run is to be reported separately unsupportedoperationexception; Numberformatexception;nullpointerexception exception, these are runtime Error

Type annotations are used to support strong type checking in Java programs. With the plug-in check framework, runtime error can be detected at compile time to improve code quality. This is the role of the type annotation.

Third, the check framework

The check framework is a Third-party tool, with Java type annotation effect is 1+1>2. It can be embedded in the Javac compiler and can be used with Ant and Maven, or as an Eclipse plug-in. The address is http://types.cs.washington.edu/checker-framework/.
The check framework can find where type annotations appear and check for a simple example:

Copy Code code as follows:

Import checkers.nullness.quals.*;
public class Getstarted {
void sample () {
@NonNull Object ref = new Object ();
}
}

Using Javac to compile the above class

Copy Code code as follows:

Javac-processor Checkers.nullness.NullnessChecker Getstarted.java

Compilation is passed, but if modified into:

Copy Code code as follows:

@NonNull Object ref = NULL;

If you do not want to use type annotations to detect errors, you do not need processor, direct Javac Getstarted.java can be compiled, which is available in the Java 8 with type Annotation support version, but Java The 5,6,7 version doesn't work because the Javac compiler doesn't know what @nonnull is, but the check framework has a backward-compatible solution, which is to annotate the type annotation nonnull with/**/
, such as the above example modified to:

Copy Code code as follows:

Import checkers.nullness.quals.*;
public class Getstarted {
void sample () {
/* @NonNull */Object ref = NULL;
}
}

The Javac compiler ignores the annotation block, but the Javac compiler inside the check framework can also detect nonnull errors.
By type annotation +check Framework we can see that now runtime error can be found at compile time.

Iv. about JSR 308

JSR 308 wants to address two issues that arise in the Java 1.5 annotations:

1. Syntactic limitations on annotations: Only write notes in the Declaration
2. Semantic limitations of the type system: the type system does not prevent all bugs
JSR 308 solves both of these problems by using the following methods:

1. Expand the syntax of the Java language to allow annotations to appear in more locations. Includes: Method Receiver (Methods receivers, example public int size () @Readonly {...} ), generic parameters, arrays, type conversions, type tests, object creation, type parameter bindings, class inheritance, and throws clauses. is actually a type annotation and is now a feature of Java 8

2. A more powerful annotation processor can be created by introducing a pluggable type system (pluggable type systems). The Type checker analyzes the source code with a type-qualified annotation and generates a warning message when it finds errors such as mismatches. It's actually the check framework.
Against the JSR308, some objected, and felt more complex and static, such as

Copy Code code as follows:
@NotEmpty list< @NonNull string> strings = new arraylist< @NonNull string> () >

Change to dynamic language for
Copy Code code as follows:
var strings = ["One", "two"];

Some people agree that, in the final analysis, the code is the "most fundamental" document. The annotations contained in the code clearly indicate the intent of the code writer. When there is no timely update or omission, it is the intent information contained in the annotations that is most easily lost in other documents. And the Run-time errors are transferred to the compile phase, not only to speed up the development process, but also to save time to check bugs when testing.

V. Summary

Not everyone likes this trait, in particular, dynamic language is more popular today, fortunately, Java 8 does not require everyone to use this feature, opponents can not use this feature, and some of the code quality requirements of higher people or companies can use JSR 308, after all, the code is "the most basic" document, I agree with this remark. Although the code will increase, it can make your code more expressive. What do you think of this feature?

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.