Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Whether type annotations become more complex or convenient in Java 8

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

It is believed that many inexperienced people have no idea about whether the type annotation in Java 8 becomes complex or convenient. Therefore, this article summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

As we all know, the addition of this feature to java5 has sprung up everywhere and has been widely used in many frameworks to simplify the configuration of programs. What on earth is the controversial type comment? Complex or convenient?

What is a type annotation

Before java 8, annotations could only be used in declared places, such as classes, methods, and properties; in java 8, annotations could be applied anywhere, such as:

Create a class instance

New @ Interned MyObject ()

Type mapping

MyString = (@ NonNull String) str

In the implements statement

Class UnmodifiableList implements @ Readonly List {...}

Throw exception statement

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

It is important to note that type annotations are only grammatical, not semantic, and do not affect the compile time, load time, and run time of java, that is, type annotations are not included when compiled into class files.

The role of type annotation

Take a look at the following code first

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

The above code is compiled through, but the run will report UnsupportedOperationException; NumberFormatException;NullPointerException exceptions separately. These are all runtime error.

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

Check framework

Check framework is a third-party tool, and the effect of type annotations with Java is 1: 1 > 2. It can be embedded in the javac compiler, can be used with ant and maven, or can be used 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, for a simple example:

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

Compile the above class using javac

Javac-processor checkers.nullness.NullnessChecker GetStarted.java

The compilation is passed, but if you modify it to

@ NonNull Object ref = null

When compiled again, it appears

GetStarted.java:5: incompatible types. Found: @ Nullable required: @ NonNull Object @ NonNull Object ref = null; ^ 1 error

If you don't want to use type annotations to detect errors, you don't need processor. Direct javac GetStarted.java can be compiled and passed, which is possible in the java 8 with Type Annotation Support version, but not even in java 5, with Type Annotation Support 6 and 7, because the javac compiler doesn't know what @ NonNull is, but check framework has a backward compatible solution, which is to annotate the type annotation nonnull with / * /.

For example, the above example is modified to

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

In this way, the javac compiler ignores the comment blocks, but the javac compiler in check framework can also detect nonnull errors.

We can see from the type annotation + check framework that runtime error can now be found at compile time.

About JSR 308

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

Syntactic restrictions on annotations: comments can only be written in the place of the declaration

Semantic limitations of the type system: the type system does not prevent all bug

JSR 308 solves the above two problems by:

The syntax of Java language is extended to allow annotations to appear in more places. Include: method receiver (method receivers, example public int size () @ Readonly {...}), generic parameters, arrays, type conversions, type testing, object creation, type parameter binding, class inheritance, and throws clauses. It's actually a type annotation, and it's now a feature of java 8.

More powerful annotation processors can be created by introducing a pluggable type system (pluggable type systems). The type checker analyzes the source code with type-qualified annotations and generates a warning message when errors such as mismatches are found. Actually, it's check framework.

Some people object to JSR308 and find it more complex and static, such as

@ NotEmpty List strings = new ArrayList () >

Replace it with a dynamic language

Var strings = ["one", "two"]

Some people agree that, in the final analysis, code is the "most fundamental" document. The comments contained in the code clearly indicate the intention of the code writer. When there is no timely update or omission, it is precisely the intention information contained in the comments that is most likely to be lost in other documents. And transferring run-time errors to the compilation phase can not only speed up the development process, but also save time checking bug during testing.

Summary

Not everyone likes this feature, especially when dynamic languages are more popular today, fortunately, java 8 does not force everyone to use this feature, opponents can not use this feature, and some people or companies with higher requirements for code quality can use JSR 308. after all, the code is the "most basic" document, which I agree with. Although the code will increase, it can make your code more expressive. Everyone expresses their views on this feature.

After reading the above, have you mastered whether type annotations in Java 8 become more complex or convenient? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report