Annotation (note) Introduction:
Note the most impressive possibility is that JUnit does the unit test and uses it in various frameworks. This article mainly briefly introduces the use of annotations, the next article in-depth study.
annotation does not directly affect code semantics, but it can be seen as a program-like tool or class library, which in turn has an impact on the running program semantics.
Annotation can be read from source files, class files, or in various ways that are reflected at run time
The Java annotation system comes with the following main 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 customize annotations:
You only need to use @interface to define an annotation, for example:
[Java]View Plaincopy print?
- Use @interface to declare an annotation (actually automatically inherits the Java.lang.annotation.Annotation interface)
- Public @interface Annotationtest {
- String value1 () default "Hello"; //Set the String Type property Value1 for the annotation and set the default value using the Defalut keyword
- Enumtest value2 (); //Set value2 for enumeration type
- String[] Value3 (); //Set Value3 of array type
- }
How to use annotations, as follows:
[Java]View Plaincopy print?
- @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 on properties, methods, and classes.
You need to assign a value to a property using Name=value, because value1 sets the default property, so you can ignore it, and if you don't set a default, all of the properties are assigned values.
There is also a special case, if the annotation only defines an attribute, the name is value, then you can directly assign the value, do not need to use the Name=value this assignment method, as follows:
[Java]View Plaincopy print?
- Public @interface Annotationtest {
- String value ();
- }
- @AnnotationTest ("test")
- Public Void Method () {
- System.out.println ("Usage of Annotation");
- }
"Annotations" for retouching annotations
Annotations can also add annotations to the "annotations" to decorate, commonly used in the following two, one is retention, a target
Retention:
Using retention, you must provide an enumeration for the Java.lang.annotation.RetentionPolicy type.
The Retentionpolicy enumeration has the following 3 types:
SOURCE : Completes the task when the program is compiled with annotation information
class: The compiler stores annotation in a CLASS file and cannot be read into by the virtual machine
RUNTIME: The compiler stores the annotation in the class file, which can be read by the virtual machine
With these three kinds of retention prolicy you can decide whether annotations are read from source files, class files, or reflected at run time
Examples of retention in the last
Target:
Use Java.lang.annotation.Target to define where annotations are used
Similarly, when using a Java.lang.annotation.ElementType to specify an enumeration value type of 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
As follows: Define an annotation mytarget, set the target type as method to modify the annotation so that the annotation can only be labeled on method
[Java]View Plaincopy print?
- @Target (Elementtype.method)
- Public @interface Mytarget {
- String Hello () default "Hello";
- }
[Java]View Plaincopy print?
- @MyTarget //There will be an error, because he is marked on the class
- Public class Mytargettest {
- @MyTarget //callout does not error on method
- public void DoSomething () {
- System.out.println ("Hello World");
- }
- }
invoking annotations using reflection
In the following classes, 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 () gets all the annotation that have been declared
isannotationpresent (class<? extends annotation> Annotationclass) Whether this annotation appears
With these methods, we can get the contents of the annotations when the program is running, with the following examples:
[Java]View Plaincopy print?
- @Retention (Retentionpolicy.runtime) //define an annotation and use the Retention callout as RUNTIME
- Public @interface Myannotation {
- String Hello () default "Hello";
- String World ();
- }
The note is marked as the runtime type, indicating that the note can be saved in the class file and read to the Java Virtual machine at run time
[Java]View Plaincopy print?
- @Retention (Retentionpolicy.class) //define an annotation, Retention labeled as runtime
- Public @interface MyAnnotation2 {
- String Hello () default "Hello"; //Set the default value to Hello
- }
Another custom annotation retention marked as class
[Java]View Plaincopy print?
- Public class MyTest {
- @SuppressWarnings ("unchecked") //java Annotated retention's policy is source
- @Deprecated //java Annotations Retention's policy is runtime
- @MyAnnotation (name="Dean", age=") //Custom annotations retention policy is runtime
- @MyAnnotation2 //Custom annotations retention policy is class
- public void TestMethod () {
- System.out.println ("This is a method");
- }
- }
Define a TestMethod method that gives him 4 annotations, of which 2 Java comes with 2 that we customize. The retention properties of the annotations are different.
The following defines a test class to validate the results:
[Java]View Plaincopy print?
- Public static void Main (string[] args) throws Exception {
- MyTest MyTest = new MyTest ();
- //Get the TestMethod method by reflection
- class<mytest> C = MyTest. class;
- method = C.getmethod ("TestMethod", new class[]{});
- method Isannotationpresent () in the//annotatedelement interface to determine whether an incoming annotation type exists
- if (method.isannotationpresent (myannotation. Class)) {
- Method.invoke (MyTest, new object[]{});
- method Getannotation () in the//annotatedelement interface to get annotations of the incoming annotation type
- Myannotation myannotation = method.getannotation (myannotation. Class);
- //Get the attributes 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 to 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 ());
- }
- }
Print Result: This is a method
Name:dean age:25
-----------------------------------
java.lang.Deprecated
Gxy.text.annotation.MyAnnotation
Split Line: Describes how to use methods and reflections in the Annotatedelement interface to invoke annotations
Under Split line: It proves that only annotations that define the retention policy as runtime can be read by reflection.
The next article analyzes the use and rationale of reflection and annotations in JUnit
Java Reflection Learning Summary Five (Annotation (annotations)-Basic article)