Annotation (note) briefly describes:
Note the most impressive possibility is that JUnit does the unit test and uses it in various frameworks.
This article mainly introduces the use of annotations, the next article further in-depth study.
annotation does not directly affect code semantics. But it can be seen as a tool or class library of similar programs. This in turn has an impact on the program semantics being executed.
Annotation can be read from source files, class files, or in various ways that are reflected at execution time
The Java annotation system comes with the main following annotations:
The override annotation represents the corresponding method of the subclass to override (override) the parent class
Deprecated Annotation representation method is not recommended to be used
Suppress Warnings annotations indicate suppression warnings
How to define annotations yourself:
Just use @interface to define an annotation, such as:
Use @interface to declare an annotation (which is actually the Java.lang.annotation.Annotation interface itself) public @interface annotationtest {String value1 () Default "Hello"; Set the String Type property Value1 for the annotation and use Defalutkeyword to set the default value Enumtest value2 ();//Set the enumeration type of value2string[] value3 ();// Sets the array type of VALUE3}
How to use annotations, such as the following:
@AnnotationTest (value2 = enumtest.age, value3={""}) public class Annotationusage {@AnnotationTest (value1 = "Test", value2 = Enumtest.name, value3={""}) String test, @AnnotationTest (value1 = "Test", value2 = Enumtest.name, value3={""}) public void Method () {System.out.println ("Usage of Annotation");}}
As above, annotations can be labeled in attributes. Method. Class.
It is necessary to assign a value to a property using an assignment such as Name=value, because value1 sets the default property, so it can be ignored, assuming that no default value is set, all properties are assigned values.
In another special case, assuming that the annotation only defines an attribute and the name is value, then it is possible to assign a value directly without using an assignment such as Name=value. For example, the following:
Public @interface Annotationtest {String value ();} @AnnotationTest ("test") public void Method () {System.out.println ("Usage of Annotation");}
"Annotations" for retouching annotations
Annotations can also be added to the annotated "annotations" to be modified, often using the following two, one is retention. A target
Retention:
Using retention is required to provide an enumeration of type Java.lang.annotation.RetentionPolicy
The Retentionpolicy enumeration has the following 3 types:
SOURCE : The task is finished when the program is compiled with annotation information
class: The compiler stores annotation in the CLASS file and cannot be read by the virtual machine
RUNTIME: The compiler stores the annotation in the class file. Can be read into by a virtual machine
With these three kinds of retention prolicy can decide that annotations are from the source file. class file or the reflection is read at execution time
Examples of retention in the last
Target:
Use Java.lang.annotation.Target to define where annotations are used
The same, when used to specify a Java.lang.annotation.ElementType enumeration value type for his "properties"
The types of ElementType enumerations are as follows:
Annotation_type: Suitable for ANNOTATION
CONSTRUCTOR: suitable for construction methods
field: applies To field
local_variable: suitable for local variables
method: applies to methods
Package: for the package
PARAMETER: Suitable for PARAMETER on method
TYPE: for Class,interface,enum
For example, the following: Defines an annotation mytarget. Set the target type to be a method to decorate this annotation. So this annotation can only be labeled in method.
@Target (elementtype.method) public @interface mytarget {String hello () default "Hello";}
@MyTarget //here will be error, because he marked on the class public class Mytargettest {@MyTarget //Callout on the method will not error public void DoSomething () { System.out.println ("Hello World");}}
invoking annotations using reflection
In the following class, class Constructor Field method package and other classes implement the Annotatedelement interface in the interface has the following important methods:
getannotations (Class annotationtype)Gets a specified type of annotation
getannotations ()Get all the annotation
getdeclaredannotations ()Get all the annotation that have been declared
isannotationpresent (class<? extends annotation> Annotationclass)Whether this annotation appears
With these methods, we can get the annotated content when the program executes with the reflection. Examples include the following:
@Retention (Retentionpolicy.runtime)//define an annotation. Use retention callout as Runtimepublic @interface myannotation {String hello () default "Hello"; String World ();
The note is marked as the runtime type, indicating that the note is finally saved in the class file and is read to the Java virtual machine when it executes
@Retention (Retentionpolicy.class)//define an annotation. Retention labeled Runtimepublic @interface MyAnnotation2 {String hello () default "Hello";//set default = Hello}
One of your own definitions is a note retention marked as class
public class MyTest {@SuppressWarnings ("unchecked") //java comes with annotations retention's policy is source@deprecated// Java's own annotated retention policy is runtime@myannotation (name= "Dean", age= "25")// The policy for the annotated retention, defined by itself, is classpublic void TestMethod (), which is defined by runtime@myannotation2//'s own annotated retention. System.out.println ("This is a method");}}
Defines a TestMethod method. He was marked with 4 annotations. Of the 2 Java comes with, 2 of which we define ourselves. The retention attribute of the annotation is not the same.
The following defines a test class to verify the results:
public static void Main (string[] args) throws Exception {MyTest MyTest = new MyTest ();//The TestMethod method is obtained by reflection Class<mytest > c = mytest.class; method = C.getmethod ("TestMethod", New class[]{}), Methods Isannotationpresent () in the//annotatedelement interface, Infer if the incoming annotation type exists if (Method.isannotationpresent (Myannotation.class)) {Method.invoke (myTest, New object[]{});// Annotatedelement method Getannotation () in the interface, gets the annotation of the incoming annotation type myannotation myannotation = method.getannotation ( Myannotation.class);//Get the attribute in the annotation string name = Myannotation.name (); String age = Myannotation.age (); System.out.println ("Name:" +name + "Age :" +age);} System.out.println ("-----------------------------------"); method Getannotations () in the//annotatedelement interface, Get all annotations annotation[] annotations = method.getannotations ();//loop annotation array prints the name of the annotation type for (Annotation annotation:annotations) { System.out.println (Annotation.annotationtype (). GetName ());}}
Printing results are:
This is a method
Name:dean age:25
-----------------------------------
java.lang.Deprecated
Gxy.text.annotation.MyAnnotation
Cutting line: Describes how to invoke annotations using methods and reflections in the Annotatedelement interface
Under the cutting line: It proves that only the retention-defined policy is a runtime annotation capable enough to be reflected and read.
The next article analyzes the use and rationale of reflection and annotations in JUnit
Java Reflection Learning Summary Five (Annotation (annotations)-Basic article)