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

The difference between Java8 repeated annotations and type annotations

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly explains the difference between Java8 repeated annotations and type annotations. The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn the difference between Java8 repeated annotations and type annotations.

Catalogue

Repeated annotations and type annotations for new features of Java8

I. Notes in JDK5

1. Comments (@)

two。 Action

3. How to understand notes?

4. About annotations

5. Annotations are divided into three stages

6. Attribute type of the annotation

7. Add attributes to comments

II. Notes in Java8

1. Type annotation

two。 Repetitive annotation

III. Java8's enhancement of annotations

Repeated annotations and type annotations for new features of Java8

Before Java8, when annotating a class or method, field, or parameter, the same comment could only be annotated once. But in Java8, repeated comments and type comments have been added, that is, starting from Java8, multiple identical comments are supported on a class or method, field, or parameter. So, some readers will ask: how to achieve it? Don't worry, look down! This article is not just a note in Java8.

1. Note 1 in JDK5. Comments (@)

Annotations are equivalent to a kind of tag, and adding comments to the program is tantamount to adding some kind of tag to the program. (what's new in JDK1.5).

two。 Action

Tell the javac compiler or java development tool... Send a message to it as a mark.

3. How to understand notes?

An annotation is a class.

Tags can be added to packages, classes, fields, methods, method parameters, and local variables. Multiple annotations can exist at the same time.

There is no ";" or other special symbol at the end of each comment.

The basic annotation information required to define annotations is shown below.

@ SuppressWarnings ("deprecation") / / Compiler warns that obsolete (source phase) @ Deprecated / / obsolete (Runtime phase) @ Override / / rewrite (source phase) @ Retention (RetentionPolicy.RUNTIME) / / leave comments to the program runtime. (Runtime phase) @ Target ({ElementType.METHOD,ElementType.TYPE}) / / tags can be defined not only on methods, but also on classes, interfaces, enumerations, etc.

Note:

1) adding comments requires an annotation class. RetentionPolicy is an enumerated class (with three members).

2) arrays can be stored in Target. Its default value is any element.

ElementType.METHOD: indicates that it can only be marked on a method.

ElementType.TYPE: indicates that tags can only be defined on classes, interfaces, enumerations, etc.

3) ElementType is also an enumeration class. Members include: ANNOTATION_TYPE (annotations), CONSTRUCTOR (constructors), FIEID (member variables), LOCAL_VARIABLE (variables), METHOD (methods), PACKAGE (packages), PARAMETER (parameters), TYPE.

4. About annotations

Meta-annotations: annotations of annotations (understanding: to annotate an annotated class)

Metadata: data of data

Meta-information: information of information

5. Annotations are divided into three stages

Java source file-> class file-- > bytecode in memory.

There are three values for Retention's comments: (corresponding to the three stages of the annotation)

RetentionPolicy.SOURCE

RetentionPolicy.CLASS

RetentionPolicy.RUNTIME

Note: the default phase for annotations is Class.

6. Attribute type of the annotation

Primitive types (that is, the eight basic data types), String types, Class types, array types, enumerated types, annotation types.

7. Add attributes to comments

Value: is a special property. If there is only one value property that needs to be set when setting the value, or if all other properties use the default value, then value= can be omitted and the set value can be written directly.

For example:

@ SuppressWarnings ("deprecation")

Specify the default value (default) for the property:

For example:

String value () default "blue"; / / defined in the annotation class

Properties of the array type:

For example:

Int [] arrayArr () default {3 arrayArr () 5}; / / define SunAnnotation in the annotation class (arrayArr= {3 record9) / / set the array value

Note: if there is only one element in the array attribute, the curly braces can be omitted in the attribute value section.

For example:

SunAnnotation (arrayArr=9)

Properties of enumerated types:

For example:

EnumDemo.TrafficLamp lamp ()

Enumerated type properties are defined in the annotation class. The custom enumeration class EnumDemo.java is used here and the relevant code is not given. This is just an example.

Default EnumDemo.TrafficLamp.RED

Properties of the annotation type:

For example:

MetaAnnotation annotationAttr () / / is defined in an annotation class and specifies the default value. / / this attribute is associated with the annotation class: MetaAnnotation.java, default @ MetaAnnotation ("lhm"); / / sets the annotation attribute value @ SunAnnotation (annotationAttr=@MetaAnnotation ("flx")) 2. Annotations in Java8

For annotations (also known as metadata), Java 8 has two main improvements: type annotations and repeated annotations.

1. Type annotation

1) Type annotations in Java 8 extend the scope of annotations.

Before java8, annotations can only be used where they are declared. With java8, annotations can be applied anywhere.

For example:

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 {...}

Note:

In Java 8, annotations can be used when declaring variables or parameters when type conversions or even assigning new objects.

Java annotations can support any type.

Type annotations are syntactic, 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.

2) add ElementType.TYPE_USE and ElementType.TYPE_PARAMETER (on Target)

Two new annotated program element types ElementType.TYPE_USE and ElementType.TYPE_PARAMETER are added to describe the new situation of annotations.

ElementType.TYPE_PARAMETER indicates that the annotation can be written in a declaration statement of a type variable.

ElementType.TYPE_USE means that the annotation can be written in any statement that uses types (for example, types in declaration statements, generics, and cast statements).

For example, the following example.

Target ({ElementType.TYPE_PARAMETER, ElementType.TYPE_USE}) @ interface MyAnnotation {}

3) the function of type annotation

Type annotations are used to support strong type checking in Java programs. With the third-party plug-in tool Checker Framework (note: this plug-in so easy, not described here), runtime error can be detected at compile time (for example, UnsupportedOperationException; NumberFormatException;NullPointerException exceptions are all runtime error) to improve code quality. This is what type annotations are for.

Note: use Checker Framework to find out where type comments appear and check them.

For example, the following code.

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

Compile the above class using javac: (of course it won't be so troublesome if you download the Checker Framework plug-in)

Javac-processor checkers.nullness.NullnessChecker TestDemo.java

The above compilation is passed, but if you modify the code:

@ NonNull Object my = null

However, if you do not want to use type annotations to detect errors, you do not need processor, normal javac TestDemo.java can be compiled, but the runtime will report a NullPointerException exception.

In order to automatically detect such exceptions during compilation, type annotations and Checker Framework can be used to detect errors and exceptions in advance.

Note that annotations @ NonNull are not supported in java 5 NonNull 6 and 7 versions, but checker framework has a backward compatible solution to annotate @ type annotations with / * * /.

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

In this way, the javac compiler ignores the comment blocks, but the javac compiler in checker framework can also detect @ NonNull errors.

Runtime error can be found at compile time through type annotations + checker framework.

two。 Repetitive annotation

Allows the same annotation to be used multiple times on the same declaration type (class, property, or method).

The limitation of using annotations in previous versions of Java8 is that the same annotations can only be used once in the same location, not multiple times.

Java 8 introduces a mechanism for repeating annotations so that the same annotations can be used multiple times in the same place. The repetitive annotation mechanism itself must be annotated with @ Repeatable.

In fact, repeated annotations are not a language change, but a change at the compiler level, and the technical level is still the same.

For example, we can use the following example to specifically compare previous versions of Java8 with annotations in Java8.

* * 1) * * customize a wrapper class Hints annotation to place a specific set of Hint annotations

Interface MyHints {Hint [] value ();} @ Repeatable (MyHints.class) @ interface Hint {String value ();}

Use the wrapper class as a container to store multiple comments (older version of the method)

MyHints ({@ Hint ("hint1"), @ Hint ("hint2")}) class Person {}

Use multiple annotations (new method)

@ Hint ("hint1") @ Hint ("hint2") class Person {}

* * 2) * * the complete class test is shown below.

Public class RepeatingAnnotations {@ Target (ElementType.TYPE) @ Retention (RetentionPolicy.RUNTIME) public @ interface Filters {Filter [] value (); @ Target (ElementType.TYPE) @ Retention (RetentionPolicy.RUNTIME) @ Repeatable (Filters.class) public @ interface Filter {String value () } @ Filter ("filter1") @ Filter ("filter2") public interface Filterable {} public static void main (String [] args) {for (Filter filter: Filterable.class.getAnnotationsByType (Filter.class)) {System.out.println (filter.value ());}

Output result:

Filter1

Filter2

Analysis:

The annotation Filter is annotated by @ Repeatable (Filters.class). Filters is just a container that holds Filter, and the compiler tries to hide its existence from programmers. In this way, the Filterable interface can be annotated by Filter twice.

In addition, the reflected API provides a new method getAnnotationsByType () to return the type of duplicate comments (note that Filterable.class.getAnnotation (Filters.class) will return the Filters instance injected by the compiler.

* * 3) * * there are solutions for reusing annotations before java 8, but the readability is not good.

Public @ interface MyAnnotation {String role ();} public @ interface Annotations {MyAnnotation [] value ();} public class RepeatAnnotationUseOldVersion {@ Annotations ({@ MyAnnotation (role= "Admin"), @ MyAnnotation (role= "Manager")) public void doSomeThing () {}}

The implementation of Java8 (using another annotation to store repetitive annotations, and when in use, using stored annotations Authorities to extend repeated annotations) makes it more readable.

@ Repeatable (Annotations.class) public @ interface MyAnnotation {String role ();} public @ interface Annotations {MyAnnotation [] value ();} public class RepeatAnnotationUseOldVersion {@ MyAnnotation (role= "Admin") @ MyAnnotation (role= "Manager") public void doSomeThing () {}}

What? Don't you get it? Then one more wave!

III. Java8's enhancement of annotations

Java 8 provides two improvements to annotation processing: repeatable annotations and annotations that can be used for types. Generally speaking, it is relatively simple, so let's illustrate the repeated comments and type comments in Java8 in the form of examples.

First, let's define an annotation class BingheAnnotation, as shown below.

Package io.mykit.binghe.java8.annotition;import java.lang.annotation.*;/** * @ author binghe * @ version 1.0.0 * @ description definition Notes * / @ Repeatable (BingheAnnotations.class) @ Target ({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.CONSTRUCTOR, ElementType.LOCAL_VARIABLE,ElementType.TYPE_PARAMETER}) @ Retention (RetentionPolicy.RUNTIME) public @ interface BingheAnnotation {String value ();}

Note: there is a @ Repeatable (BingheAnnotations.class) annotation on the BingheAnnotation annotation class than ordinary annotations, and some friends will ask: what is this? This is the key to defining repeatable annotations in Java8. As for BingheAnnotations.class, don't worry, just read on.

Next, we define a BingheAnnotations annotation class, as shown below.

Package io.mykit.binghe.java8.annotation;import java.lang.annotation.*;/** * @ author binghe * @ version 1.0.0 * @ description definition Notes * / @ Target ({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.CONSTRUCTOR, ElementType.LOCAL_VARIABLE,ElementType.TYPE_PARAMETER}) @ Retention (RetentionPolicy.RUNTIME) public @ interface BingheAnnotations {BingheAnnotation [] value ();}

See here, everyone understand! Yes, BingheAnnotations is also an annotation class, which lacks a @ Repeatable (BingheAnnotations.class) annotation compared to the BingheAnnotation annotation class, that is, the definition of the BingheAnnotations annotation class is almost no different from that of ordinary annotations. It is worth noting that in the BingheAnnotations annotation class, we define an array of BingheAnnotation annotation classes, that is, there are multiple BingheAnnotation annotations in the BingheAnnotations annotation class. Therefore, specify @ Repeatable (BingheAnnotations.class) on the BingheAnnotation annotation class to indicate that BingheAnnotation annotations can be reused on classes, fields, methods, parameters, constructors, and parameters.

Next, we create a Binghe class, define an init () method in the Binghe class, and on the init method, reuse the @ BingheAnnotation annotation to specify the appropriate data, as shown below.

Package io.mykit.binghe.java8.annotation;/** * @ author binghe * @ version 1.0.0 * @ description Test Notes * / @ BingheAnnotation ("binghe") @ BingheAnnotation ("class") public class Binghe {@ BingheAnnotation ("init") @ BingheAnnotation ("method") public void init () {}}

At this point, we can test the repeated annotations, create the class BingheAnnotationTest, and test the duplicate annotations, as shown below.

Package io.mykit.binghe.java8.annotation;import java.lang.reflect.Method;import java.util.Arrays;/** * @ author binghe * @ version 1.0.0 * @ description Test Notes * / public class BingheAnnotationTest {public static void main (String [] args) throws NoSuchMethodException {Class clazz = Binghe.class; BingheAnnotation [] annotations = clazz.getAnnotationsByType (BingheAnnotation.class); System.out.println ("repeated comments on the class are as follows:") Arrays.stream (annotations) .forEach ((a)-> System.out.print (a.value () + ")); System.out.println (); System.out.println (" = = "); Method method = clazz.getMethod (" init "); annotations = method.getAnnotationsByType (BingheAnnotation.class); System.out.println (" repetitive notes on the method are as follows: ") Arrays.stream (annotations) .forEach ((a)-> System.out.print (a.value () + "));}}

Run the main () method to output the following result information.

The repeated comments on the class are as follows: binghe class = = repeated notes on the method are as follows: init method Thank you for reading, the above is the content of "the difference between Java8 repeated comments and type notes". After the study of this article, I believe you have a deeper understanding of the difference between Java8 repeated notes and type notes, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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