Java annotation Learning

Source: Internet
Author: User

Reprinted from: http://william750214.javaeye.com/blog/298104

Role of metadata

If you want to classify the role of metadata, there is no clear definition yet. However, we can divide it into three categories based on its role:

L compile the document: generate the document through the metadata identified in the code.

L code analysis: analyze the Code through the metadata identified in the code.

L compilation check: the compiler can perform basic compilation check through the metadata identified in the code.

 

Basic built-in annotations

@ OverrideAnnotations can be checked during compilation. You can add this annotation for your method to declare that this method is used to overwrite the methods in the parent class. If this method does not overwrite the parent class, an error will be reported during compilation. For example, we rewrite toString () for a certain type of method but write tostring (), and we add @ Override annotation for this method;

@ DeprecatedThe function is to add comments to methods that should not be used. When programmers use these methods, a prompt will be displayed during compilation, it has the same functions as the @ deprecated mark in javadoc. To be precise, it is not as good as javadoc @ deprecated because it does not support parameters,

Note: For details, use-Xlint: deprecation to re-compile.

@ SuppressWarningsDifferent from the first two annotations, you need to add a parameter to use it correctly. These parameter values have been defined and can be used selectively. The parameters are as follows:

 

Warning when deprecation uses outdated classes or methods

Warning When unchecked executes unchecked conversions. For example, when using a set, the generic type (Generics) is not used to specify the type of the set to be saved.

Fallthrough warning when the Switch block directly leads to the next situation without Break

Warning when path does not exist in the class path or source file path

Serial warning when serialVersionUID definition is missing on serializable classes

Warning when any finally clause in finally cannot be completed normally

All warnings about all the above situations

 

Note: For details, use-Xlint: unchecked to recompile.

 

Custom annotation type

Okay. Let's create an annotation type. It is similar to creating a new interface class file, but to distinguish it, we need to declare it as @ interface, as shown in the following example:

Public @ interface NewAnnotation {

 

}

 

Use custom annotation types

We have successfully created a NewAnnotation annotation type. Now let's try it. If you still remember the first part of this article, you should know that it is a tag annotation, it is easy to use, as shown in the following example:

Public class AnnotationTest {

 

@ NewAnnotation

Public static void main (String [] args ){

 

}

}

 

Add variable

In J2SE 5.0, we learned that built-in annotation @ SuppressWarnings () can use parameters. Can custom annotation define the number and type of parameters? The answer is yes, but the parameter type can only be basic type, String, Class, enumeration type, and so on, and the parameter cannot be blank. We will extend NewAnnotation to add a String-type parameter. The sample code is as follows:

Public @ interface NewAnnotation {

 

String value ();

}

The code for using this annotation is as follows: As you can see, there are two ways to use this annotation, which have been mentioned in previous articles. If you forget what is going on, go over it.

Public class AnnotationTest {

 

@ NewAnnotation ("Just a Test .")

Public static void main (String [] args ){

SayHello ();

}

 

@ NewAnnotation (value = "Hello NUMEN .")

Public static void sayHello (){

// Do something

}

}

 

Assign default value to the variable

We are constantly increasing our understanding of Java User-Defined annotations, but we still need to know how to set default values for variables in this entry, let's modify NewAnnotaion to see what it will look like. Not only are there a few more parameters, but even the class name has changed. But it is easy to understand. First, we define an enumeration type, set the parameter to this enumeration type, and assign the default value.

Public @ interface Greeting {

 

Public enum FontColor {RED, GREEN, BLUE };

 

String name ();

 

String content ();

 

FontColor fontColor () default FontColor. BLUE;

}

 

Limits the scope of comments

When the number of user-defined comments is increasing and complicated, some developers may encounter usage errors, mainly because the comments should not be used. Therefore, Java provides an ElementType Enumeration type to control the scope of use of each annotation. For example, some annotations can only be used for common methods, but not constructors. The ElementType enumeration defined in Java is as follows:

Package java. lang. annotation;

 

Public enum ElementType {

TYPE, // Class, interface, or enum (but not annotation)

FIELD, // Field (including enumerated values)

METHOD, // Method (does not include constructors)

PARAMETER, // Method parameter

CONSTRUCTOR, // Constructor

LOCAL_VARIABLE, // Local variable or catch clause

ANNOTATION_TYPE, // Annotation Types (meta-annotations)

PACKAGE // Java package

}

Next we will modify the Greeting comment to add a qualified statement for it. here we call it a Target usage method, which is also very simple, as shown below:

 

@ Target ({ElementType. METHOD, ElementType. CONSTRUCTOR })

Public @ interface Greeting {

}

As shown in the code above, only Greeting annotations are allowed to be labeled on common methods and constructor. An error message is prompted when the package declaration and class name are used.

 

Comment on the persistence Policy

Public enum RetentionPolicy {

SOURCE, // Annotation is discarded by the compiler

CLASS, // Annotation is stored in the class file, but ignored by the VM

RUNTIME // Annotation is stored in the class file and read by the VM

}

RetentionPolicy is used in a similar way as ElementType. A simple code example is as follows:

@ Retention (RetentionPolicy. RUNTIME)

@ Target ({ElementType. METHOD, ElementType. CONSTRUCTOR })

 

Docized Functions

The annotation provided by Java is similar to Javadoc. In fact, it has the advantage that developers can customize document attributes not supported by Javadoc and apply them in development. Its usage is the same as that of the first two. The simple code example is as follows:

@ Brief ented

@ Retention (RetentionPolicy. RUNTIME)

@ Target ({ElementType. METHOD, ElementType. CONSTRUCTOR })

Public @ interface Greeting {

}

 

It is worth noting that if you want to use the @ resolve ented meta annotation, you have to set the RetentionPolicy. RUNTIME persistence policy for this annotation. It is easier to understand why this is done.

 Annotation inheritance

 

Inheritance should be the most complex meta-annotation provided by Java. Its function is to control whether the annotation will affect the subclass. A simple code example is as follows:

@ Inherited

@ Brief ented

@ Retention (RetentionPolicy. RUNTIME)

@ Target ({ElementType. METHOD, ElementType. CONSTRUCTOR })

Public @ interface Greeting {

}

 

Read comments

When we want to read a comment, we implement it through reflection at runtime. If you are still impressed with the meta comment, you should remember that we need to set the persistence policy to RUNTIME, that is to say, only the annotation marked @ Retention (RetentionPolicy. RUNTIME), we can get the relevant information through reflection, the following example we will follow the code in the previous articles, it also reads comments marked by all methods of the AnnotationTest class and prints them to the console. Let's see how it is implemented:

Public class AnnotationIntro {

 

Public static void main (String [] args) throws Exception {

 

Method [] methods = Class. forName (

"Com. gelc. annotation. demo. customize. AnnotationTest ")

. GetDeclaredMethods ();

Annotation [] annotations;

 

For (Method method: methods ){

Annotations = method. getAnnotations ();

For (Annotation annotation: annotations ){

System. out. println (method. getName () + ":"

+ Annotation. annotationType (). getName ());

}

 

 

 

In Java concurrent programming, Annotation specially prepared for concurrent programming is used.
There are three main types:
1. Class Annotation (Annotation)
Like the name, These annotations are for classes. The master has the following three:
@ Immutable
@ ThreadSafe
@ NotThreadSafe

@ ThreadSafe indicates that this class is thread-safe. Whether it is really safe depends on how the real person implements it. If you add this label, it just means it. It's okay to add this annotation to classes that are not thread-safe.
@ Immutable indicates that the class is unchangeable and contains the meaning of @ ThreadSafe.
@ NotThreadSafe indicates that this class is not thread-safe. If this annotation is required for thread security, no error will be reported.

These three annotations are beneficial to users and maintainers. Users can immediately see whether this class is thread-safe. maintainers can check thread security based on this annotation. In addition, the Code analysis tool may use this annotation.

2. Domain Annotation (Annotation)
The field annotation is the annotation for the member variables in the class.
3. Method Annotation (Annotation)
Method annotation is the annotation of the methods in the class.

Domain annotation and method annotation are identified by @ GuardedBy (lock. The Lock tells the maintainer which Lock protects the status variable. In this way, we strongly recommend that the class maintainers pay attention to this.

@ GuardedBy (lock:

1. @ GuardedBy ("this") protected by the internal lock of the object
2. @ GuardedBy ("fieldName") is protected by the locks associated with the fieldName reference.
3. @ GuardedBy ("ClassName. fieldName") is locked by a static field of the class.
4. @ GuardedBy ("methodName ()") the lock object is the return value of the methodName () method, which is protected by this lock.
5. @ GuardedBy ("ClassName. class") is protected by direct lock objects of the ClassName class. Instead of the Lock Object of an instance of this class.

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.