Reprinted from: http://william750214.javaeye.com/blog/298104
The role of Meta data
If you want to classify the role of metadata, there is no clear definition, but we can according to its role, broadly can be divided into three categories:
L Write documents: Generate documents from the metadata identified in the code.
L Code Analysis: The code is analyzed by the metadata identified in the code.
L Compile Check: The metadata identified in the code allows the compiler to implement basic compilation checks.
Basic built-in annotations
@Override Annotations Enable compile-time checking, you can add the comment to your method to declare that the method is used to overwrite the method in the parent class. If the method is not a method that overrides the parent class, it will be wrong at compile times. For example, we rewrite the ToString () method for a class and write ToString (), and we add a @override comment to the method;
The role of @Deprecated is to add comments to the methods that should not be used, and when programmers use them, they will display a hint at compile time, which has the same function as the @deprecated tag in Javadoc, and, to be exact, It's not as good as Javadoc @deprecated, because it doesn't support parameters,
Note: To learn more, recompile with-xlint:deprecation.
@SuppressWarnings is different from the first two comments, you need to add a parameter to use correctly, these parameter values are already defined, we use selectively, the parameters are as follows:
Deprecation warning when an outdated class or method is used
Unchecked warnings for non-checked conversions, such as when using a collection without generics (generics) to specify the type saved by the collection
Fallthrough warning when a Switch block directly leads to the next situation without a break
Warning when path has non-existent paths in classpath, source file path, etc.
Serial warning When a SERIALVERSIONUID definition is missing on a serializable class
Finally, a warning when any finally clause does not complete properly
All warnings about all of these cases
Note: To learn more, recompile with-xlint:unchecked.
customizing annotation types
OK, let's create our own annotation type (annotation type). It is similar to creating a new interface class file, but in order to differentiate it, we need to declare it as @interface, as in the following example:
Public @interface Newannotation {
}
Use a custom annotation type
We have successfully created good one annotation type newannotation, now let's try to use it, if you remember the first part of this article, then you should know that he is a tag comment, and it is easy to use, as in the following example:
public class Annotationtest {
@NewAnnotation
public static void Main (string[] args) {
}
}
Add variable
J2SE 5.0, we learned that the built-in annotation @suppresswarnings () is available with parameters, so can custom annotations define the number and type of parameters? The answer is yes, but the parameter type is only allowed for the base type, String, Class, enum type, and so on, and the parameter cannot be empty. Let's extend the newannotation to add a string parameter to it, and the sample code is as follows:
Public @interface Newannotation {
String value ();
}
The code for using this comment is as follows: As you can see, the use of this annotation is written in two ways, as mentioned in the previous article. If you forget what's going on, then 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
}
}
Assigning a default value to a variable
Our understanding of Java custom Annotations is growing, but we also need to be more, in this article we will learn how to set the default value for the variable, we then modify the newannotaion to see what it will look like, not only a few more parameters, even the class name has changed. But it's easy to understand, we first define an enumeration type, then set the parameter to that enumeration type and give the default value.
Public @interface Greeting {
public enum FontColor {RED, GREEN, BLUE};
String name ();
String content ();
FontColor fontcolor () default fontcolor.blue;
}
Limit Comment Usage Range
As our custom annotations continue to grow more complex, it can lead to some developers using errors, mainly in places where they should not be used. To do this, Java provides a ElementType enumeration type to control the use of each annotation, for example, some annotations can only be used for common methods, not constructors, and so on. The following is a Java-defined ElementType enumeration:
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
}
Let's modify the greeting comment to add a scoped statement here, which we call the target using method is also very simple, as follows:
@Target ({elementtype.method, elementtype.constructor})
Public @interface Greeting {
}
As shown in the code above, we only allow greeting annotations to be labeled on ordinary methods and constructors, and the error message is prompted when the package declaration, class name, and so on are used.
Comment 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 to ElementType, and the simple code example is as follows:
@Retention (Retentionpolicy.runtime)
@Target ({elementtype.method, elementtype.constructor})
Documentation Features
Java-provided documented meta-annotations are similar to Javadoc, but the benefit is that developers can customize document properties that are not supported by Javadoc and apply them in development. Its use is the same for the two, and the simple code example is as follows:
@Documented
@Retention (Retentionpolicy.runtime)
@Target ({elementtype.method, elementtype.constructor})
Public @interface Greeting {
}
It is worth noting that if you want to use the @documented meta-comment, you have to set the Retentionpolicy.runtime retention policy for the comment. Why do this, it should be easier to understand, here is not mentioned.
Label Inheritance
Inheritance should be the most complex meta-comment provided by Java, and its purpose is to control whether annotations affect subclasses, and the simple code example is as follows:
@Inherited
@Documented
@Retention (Retentionpolicy.runtime)
@Target ({elementtype.method, elementtype.constructor})
Public @interface Greeting {
}
Reading comment Information
When we want to read a comment, we do it through reflection at runtime, and if you have a bit of an impression of the meta-comment, you should remember that we need to set the retention policy to runtime, which means that only comments are tagged with @retention ( Retentionpolicy.runtime), we can obtain the relevant information through reflection, the following example we will follow the previous articles in the code that appears, and to read all the methods of the Annotationtest class tag comments and print to the console. Well, let's see how it's 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, there are some Annotation that are specially prepared for concurrent programming. Mainly includes three categories: 1, Class Annotation (annotations) like names, these annotations are for classes. The master has to have the following three: @Immutable @ThreadSafe @NotThreadSafe
@ThreadSafe means that the class is thread-safe. Whether the specific is really safe, that depends on how the implementation of the implementation of the, anyway, the label is just to show. The non-thread-safe class has no problem with this annotation. @Immutable indicates that the class is immutable and contains the meaning of the @ThreadSafe. @NotThreadSafe indicates that the class is not thread-safe. If it is thread-safe to make this remark, it will not be an error.
These three annotations are useful to both the user and the maintainer, who can immediately see if the class is thread-safe, and the maintainer is able to focus on thread safety based on this annotation. In addition, the Code analysis tool may take advantage of this annotation.
2. Domain Annotation (annotation) field annotations are annotations that add to a member variable inside a class. 3, Method Annotation (annotated) method annotation is a method added to the class annotation.
Domain Annotations and method annotations are identified by @guardedby (lock). The lock inside is the one that tells the maintainer: This state variable, which is protected by which lock. This can strongly prompt the maintainer of the class to note here.
@GuardedBy (lock) is used in the following ways:
1, @GuardedBy ("This") is protected by the object's internal lock 2, @GuardedBy ("FieldName") is protected by the lock associated with the FieldName reference. 3, @GuardedBy ("Classname.fieldname") is saved by the lock of a class static field. 4, @GuardedBy ("MethodName ()") lock object is the MethodName () method, protected by this lock. 5. @GuardedBy ("Classname.class") is protected by the direct lock object of the ClassName class. Instead of a lock object for an instance of this class.
Turn: Java annotation Detailed