Home  >  Article  >  Java  >  A brief analysis of type annotations in Java8

A brief analysis of type annotations in Java8

高洛峰
高洛峰Original
2017-01-23 15:19:101412browse

Notes As we all know, this feature has been added since java5, and it has blossomed everywhere now. It is widely used in many frameworks to simplify the configuration of programs. So what exactly are the controversial type annotations? Complex or convenient?

1. What are type annotations?

Before Java 8, annotations can only be used where they are declared, such as classes, methods, properties; in Java 8, annotations can be applied to any Place, for example:

Create class instance

new @Interned MyObject();

Type mapping

myString = (@NonNull String) str;

implements statement

class UnmodifiableList<T> implements @Readonly List<@Readonly T> { ... }

throw exception statement

void monitorTemperature() throws @Critical TemperatureException { ... }

Required Note that type annotations are only syntax, not semantics, and will not affect Java's compilation time, loading time, and running time. In other words, type annotations are not included when compiled into a class file.

2. The role of type annotations

First look at the following code:

Collections.emptyList().add("One");
int i=Integer.parseInt("hello");
System.console().readLine();

The above code is compiled successfully, but when running, UnsupportedOperationException; NumberFormatException; NullPointerException will be reported respectively Exceptions, these are runtime errors;

type annotations are used to support strong type checking in Java programs. With the plug-in check framework, runtime errors can be detected during compilation to improve code quality. This is the role of type annotations.

3. check framework

check framework is a third-party tool, and the effect of using Java's type annotations is 1+1>2. It can be embedded into the javac compiler, used with ant and maven, or as an eclipse plug-in. The address is http://types.cs.washington.edu/checker-framework/.
check framework can find where type annotations appear and check them. A simple example:

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

Use javac to compile the above class

javac -processor checkers.nullness.NullnessChecker GetStarted.java

The compilation passes, but if it is modified to:

@NonNull Object ref = null;

If you don’t want to use type annotations to detect errors, you don’t need a processor. Direct javac GetStarted.java can be compiled and passed. This is possible in the java 8 with Type Annotation Support version, but java 5, Versions 6 and 7 will not work because the javac compiler does not 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 Modify it to:

import checkers.nullness.quals.*;
public class GetStarted {
    void sample() {
        /*@NonNull*/ Object ref = null;
    }
}

In this way, the javac compiler will ignore the comment block, but the javac compiler in the check framework can also detect nonnull errors.
Through the type annotation + check framework we can see that runtime errors can now be found during compilation.

4. About JSR 308

JSR 308 wants to solve two problems that appear in Java 1.5 annotations:

1. Syntactic restrictions on annotations: only Annotations can be written in the place of declaration
2. Semantic limitations of the type system: The type system cannot prevent all bugs
JSR 308 solves the above two problems through the following methods:

1. Expand the syntax of the Java language to allow annotations to appear in more positions. Includes: method receivers (Annotation: public int size() @Readonly { ... }), generic parameters, arrays, type conversions, type testing, object creation, type parameter binding, class inheritance and throws clause. In fact, it is type annotation, which is now a feature of Java 8

2. By introducing pluggable type systems, a more powerful annotation processor can be created. The type checker analyzes the source code with type qualification annotations, and will generate warning messages if errors such as mismatches are found. In fact, it is check framework
Regarding JSR308, some people object, thinking that it is more complicated and static. For example,

@NotEmpty List<@NonNull String> strings = new ArrayList<@NonNull String>()>

is replaced by a dynamic language

var strings = ["one", "two"];

. Some people agree. In the final analysis, the code is " "The most fundamental" document. Annotations included in the code clearly indicate the intent of the person who wrote the code. When it is not updated in time or there are omissions, it is precisely the intended information contained in the annotations that is most likely to be lost in other documents. Moreover, transferring runtime errors to the compilation stage can not only speed up the development process, but also save time in checking bugs during testing.

5. Summary

Not everyone likes this feature, especially today when dynamic languages ​​are more popular. Fortunately, Java 8 does not force everyone to use this feature. Those who object can do so. Using this feature, people or companies that have higher requirements for code quality can use JSR 308. After all, code is the "most basic" document. I agree with this sentence. Although the code will increase, it can make your code more expressive. Everyone has their own opinions on what they think of this feature. .

For more articles related to the brief analysis of type annotations in Java8, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn