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

What is the annotation syntax for Java 8

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

Share

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

This article mainly explains "what is the grammar of Java 8 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 "what is the grammar of Java 8 annotations".

Annotation grammar

The annotation consists of the character @ and the annotation name, @ AnnotationName. When the compiler finds the syntax the element, it parses it as an annotation. For example:

@ ExampleAnnotation

Public class SampleClass {

}

The above comment is called ExampleAnnotation and is marked on SampleClass.

Annotations can contain attributes and are given in the form of key-value pairs when declaring annotations. For example:

@ ExampleAnnotation (name = "first name", age = 35)

Public void simpleMethod () {

}

Note that ExampleAnnotation is a method annotation here. If the annotation contains only one attribute, you can ignore the attribute name when declaring the annotation. Examples are as follows:

@ ExampleAnnotation ("I am the only property")

Public void simpleMethod () {

}

Multiple annotations can be used for an element. For example, the following example:

@ Annotation1

@ Annotation2 ("Another Annotation")

Public class SimpleClass {

}

Starting with J2SE 8, you can use the same annotation multiple times for the same element, for example:

@ ExampleAnnotation ("Annotation used")

@ ExampleAnnotation ("Annotation repeated")

Public class SimpleClass {

}

This will be discussed in detail in the @ Repeatable section.

Java predefined annotations

Java supports a set of predefined annotations. The comments provided in Java Core are described below:

@ Retention:

SOURCE: annotations are only available in the source code. The compiler and JVM ignore this comment and are therefore not available at run time

CLASS: the compiler processes the annotation, but JVM does not, so it is not available at run time

RUNTIME:JVM processes the annotation and can be used at run time.

@ Target:

ANNOTATION_TYPE: other comments can be modified

CONSTRUCTOR: can modify the constructor

FIELD: fields or properties can be decorated

LOCAL_VARIABLE: can modify local variables

METHOD: can modify method

PACKAGE: can modify the package declaration

PARAMETER: method parameters can be modified

TYPE: can modify Class, Interface, Annotation, or enum declarations

PACKAGE: can modify the package declaration

TYPE_PARAMETER: parameter declarations can be modified

TYPE_USE: any type can be modified.

@ Documented:@Retention (RetentionPolicy.RUNTIME)

@ Target (ElementType.TYPE_USE)

@ Repeatable (RepeatableAnnotationContainer.class)

Public @ interface RepeatableAnnotation () {

String values ()

}

RepeatableAnnotation can repeatedly modify elements.

Next, define the RepeatableAnnotationContainer annotation type. This is an annotated type container that contains an array of RepeatableAnnotation types.

Public @ interface RepeatableAnnotationContainer {

RepeatableAnnotation [] value ()

}

Repeatable can now be annotated multiple times by an element.

@ RepeatableAnnotation ("I am annotating the class")

@ RepeatableAnnotation ("I am annotating the class again")

@ RepeatableAnnotation ("I am annotating the classfor the third time")

Publicclass RepeatedAnnotationExample {function () {/ / Foreign Exchange tracking www.gendan5.com}

To get the value in the annotation in the program, you first need to get the array in the container, and each element of the array will contain a value. For example:

@ RepeatableAnnotation ("I am annotating the class")

@ RepeatableAnnotation ("I am annotating the class again")

@ RepeatableAnnotation ("I am annotating the class for the third time")

Public class RepeatableAnnotationExample {

Public static void main (String [] args) {

Class object = RepeatableAnnotationExample.class

Annotation [] annotations = object.getAnnotations ()

For (Annotation annotation: annotations) {

RepeatableAnnotationContainer rac = (RepeatableAnnotationContainer) annotation

RepeatableAnnotation [] raArray = rac.value ()

For (RepeatableAnnotation ra: raArray) {

System.out.println (ra.value)

}

}

}

}

Execution result:

I am annotating the class

I am annotating the class again

I am annotating the class for the third time.

Type annotation

With the release of Java 8, annotations can be used for any type (Type), which means that annotations can be used wherever types are available. For example, using new operators to create class instances, type conversions, implementing interfaces with implements, throwing exceptions, and so on are called type annotations.

This annotation can help analyze and improve Java programs and provide more powerful type checking. Prior to the release of Java 8, Java did not provide a type checking framework. However, through type annotations, you can develop a type checking framework to check Java programs.

For example, suppose we want a specific variable not to be null during program execution. You can write a custom plug-in NonNull and check for specific variables with that annotation. The variable is declared as follows:

@ NonNull String notNullString

When compiling code, if you find any code that might assign a variable to null, the compiler checks for potential problems and gives an alarm.

Custom annotation

Java allows programmers to customize annotations. Customize the syntax for annotations:

Public @ interface CustomAnnotation {}

The above code creates a new CustomAnnotation comment. The @ Interface keyword can be used for custom annotations.

When customizing annotations, you must set two required properties. You can add other attributes to the definition, but these two important attributes are required, that is, @ Retention (RetentionPolicy.RUNTIME)

@ Target (ElementType.ELEMENT)

Public @ interface CustomAnnotation {

Public String name () default "Mr Bean"

Public String dateOfBirth ()

}

In the above custom annotation, Retention Policy is RUNTIME, which indicates that the annotation can be used during the JVM runtime; Target is set to ELEMENT, indicating that the annotation can modify any element and type.

In addition, it has two properties: name and dateOfBirth. Where the default value of the name property is Mr Bean and there is no default value for dateOfBirth.

Notice that the declared Method does not take any parameters or throws statements. In addition, return types are limited to String, class, enum, annotations, and arrays of the above types.

Now, you can use custom annotations like this:

@ CustomAnnotation (dateOfBirth = "1980-06-25")

Public class CustomAnnotatedClass {

}

Similarly, you can use @ Target (ElementType.METHOD) to create a custom annotation decorated method.

Get comments and attributes

Java Reflection API provides several ways to get annotations from class, method, and other elements at run time.

The AnnotatedElement interface defines all the methods, the most important of which is:

GetAnnotations (): returns all comments for the specified element, including comments that are not explicitly written when the element is defined.

IsAnnotationPresent (annotation): checks whether annotations are available on the current element.

GetAnnotation (class): gets the annotation used by the class parameter, and returns null if the parameter does not exist.

This class supports java.lang.Class, java.lang.reflect.Method, and java.lang.reflect.Field, and can be applied to almost any Java element.

The following example program shows how to get information about custom annotations:

Public static void main (String [] args) {

Class object = CustomAnnotatedClass.class

/ / get all comments from the class

Annotation [] annotations = object.getAnnotations ()

For (Annotation annotation: annotations) {

System.out.println (annotation)

}

/ / check whether there are comments

If (object.isAnnotationPresent (CustomAnnotationClass.class)) {

/ / get the required comments

Annotation annotation = object.getAnnotation (CustomAnnotationClass.class)

System.out.println (annotation)

}

/ / get comment attributes

For (Annotation annotation: annotations) {

System.out.println ("name:" + annotation.name ())

System.out.println ("Date of Birth:" + annotation.dateOfBirth ())

}

/ / perform the same operation on all methods

For (Method method: object.getDeclaredMethods ()) {

If (method.isAnnotationPresent (CustomAnnotationMethod.class)) {

Annotation annotation = method.getAnnotation (CustomAnnotationMethod.class)

System.out.println (annotation)

}

}

} Thank you for your reading, the above is the content of "Java 8 Annotation Grammar". After the study of this article, I believe you have a deeper understanding of what Java 8 Annotation Grammar has, and the specific use still 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