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 () 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: Methods ){
Annotations = method. getannotations ();
For (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.