2013年9月24日星期二

Annotation

 

start from JDK1.5 , Java increases the Annotation of this new feature , this feature is called metadata attributes , but also are called comments.

 

system built Annotation:

 

reminder : The following three systems built the Annotation in java.lang package under

 

1. @ Override , I believe we are more familiar with this If we want to override a class method when you want to add this comment, but a lot of people will ask , do not add is not the problem , but we must take into account that the program is correct , if you own intention override this method, but when you write the method name wrong, then this is not rewritten , but also changed the intent , so in the overridden method coupled with this annotation is prevention , but also clearly others tell me this method is overridden , how I was wrong method name , then the annotation will also remind me.

 

2. @ Deprecated , which means that this program element is very dangerous or there is a better choice , do not encourage the use of such elements.

 

 
  
 1 @Deprecated 
2 public class DeprecatedDemo {
3
4 @Deprecated
5 public static final String name = "xujianguo";
6
7 @Deprecated
8 public void print() {
9 System.out.println("This is the deprecated method");
10 }
11 }
 
 

described above, this class is using @ Deprecated annotation on the class , member properties , and there are methods, this class does not use up will complain , but there will be a warning message that you are using something outdated.

 

3. @ SuppressWarnings , which means that suppress the specified compiler warning devices , through this annotation we can cancel an unnecessary warnings , such as warnings and outdated generic warnings by viewing our API documentation can be found under the annotation attribute a value , the return value an array of type String , specifically : public abstract String [] value, this property is in fact a warning set, which is used to put @ SuppressWarnings can suppress the warning.

 

warning set :

                                                                                                                                                         
keyword keyword
deprecation use the deprecated class or method warning
unchecked performed unchecked conversion warnings, such as generics operations do not specify generic
fallthrough When the switch block execution to sow break statement occurs without warning
path in the class path , and so has a source file path path does not exist Warning
serial When a serializable class definition is missing serialVersionUID warning
finally finally clause can not complete any of the warning
all about all of the above warning
 

following demonstrates a suppression deprecatation and unchecked warnings Demo:

 

 
  
 1 /** 
2 * 该类实现了序列化接口,若无serialVersionUID会出现警告
3 * @author Guo
4 */
5 @SuppressWarnings({"serial", "unchecked"})
6 public class SuppressWarningsDemo implements Serializable{
7
8 public static void main(String[] args) {
9
10 /**
11 * 没有指定泛型,出现警告
12 * @author Guo
13 */
14 List<String> list = new ArrayList();
15 }
16 }
 
 

 

Custom Annotation:

 

define your own Annotation is very simple, just define an interface like :

 
  
1 [public] @interface MyAnnotation { 
2
3 }
 
 

format is simple , an Annotation may receive a variety of parameters , such as SuppressWarnings annotations , which can receive an array , here we introduce a its parameters are defined :

 

1. fundamental variables , which can be of type String , it can be of type int , the format : public type variable name ( ) ; < / span>

 

2. array type , the array definition format is also very much the same : public Type [ ] variable name ();

 

3. enum type , by defining an enumerated type , you can define annotations inside the content, format : Format : public enum variable name () ;

 

4. default values ​​, default values ​​written in Annotation , using annotations in another class when you can not write the value of format : public type variable name () default default ;

 

following simple demonstration, let us look deeper impression :

 
  
 1 enum MyEnum { 
2 xp, win7, linux;
3 }
4
5 public @interface MyAnnotation {
6
7 public String name() default "xujianguo";
8 public int age() default 20;
9 public String[] array();
10 public MyEnum system() default MyEnum.linux;
11 }
12
13 class Test {
14
15 @MyAnnotation(name="zyp", age=20, array = {"zhou", "yan", "ping"}, system=MyEnum.win7)
16 public static void main(String[] args) {
17 System.out.println("Just Test");
18 }
19 }
 
 

Now we are going to discuss a problem, you will be able to customize a good run in the JVM do, in fact, you look at the API system built the three annotation, they all use an annotation @ Retention, java.lang.annotation package under this annotation in fact, this package there are several annotation, we also introduced a , but the point is that @ Retention:

 

1. @ Documented , indicates a certain type of comment by javadoc and similar tools by default documented. You should use this type to annotate these types of statements : their comments would affect its clients to use annotated elements . If the type declaration is annotated with Documented , its comments will be annotated element as part of the public API . Simply means that the use of this annotation , after you use the Annotation , when coupled with the above comments will be recorded to the document .

 

2. @ Inherited , indicating annotation type is automatically inherited . If the annotation type declaration exists Inherited meta-annotation , and the user queries in a certain class of the annotation type declaration , but such a statement is not this type of comment , then in the class superclass automatically query the annotation type. This process is repeated until you find this type of comment or reaches the top of the class hierarchy (Object) so far. If you do not have that type of super class notes , the query will indicate the current class is no such comments. Simply means that this annotation is equivalent extends ah , the parent class if they have a comment, that this comment is in a subclass have, through reflection can also get information on the comment .

 

3. @ Target , indicating an annotation type is applicable types of program elements . If the annotation type declaration Target meta-annotation does not exist , then the declared type can be used in any program element. If there is such a meta-annotation , the compiler will enforce the specified use restrictions. Simply put this is to restrict our Annotation annotation can be used in any place, it has a value attribute is ElementType type , ElementType specified in the following range :

                                                                                                                                                                           

range

Description

ANNOTATION_TYPE

statement can only be used in a comment on

CONSTRUCTOR

can only be used in the constructor method

FIELD

only be used in the field declaration

LOCAL_VARIABLE

only be used in a local variable declaration

METHOD

only be used in the method declaration

PACKAGE

only be used in the package declaration

PARAMETER

only be used in the parameter declaration

TYPE

only be used in classes, interfaces, enumerations types

 

reminder : In fact, the scope of these restrictions can be superimposed , for example, your Annotation want to use in the class or method , can write : @ Target (ElementType.TYPE, ElementType.METHOD)

 

4. @ Retention , annotation type annotations indicating how long you want to keep . This comment has a value of the property, the property is of type RetentionPolicy, while RetentionPolicy there are three common variables, we often take a look at these three variables .

                                                                                 
range Description
SOURCE this Annotation information will only be saved in the program source file (java file ) , does not remain in the compiled file (class file )
CLASS

this Annotation of information retained in the program source file (java file ) and compiled files (class files ) , use such time

Annotation information will not be loaded into the JVM, if an Annotation not declared using what extent , this is the default range.

RUNTIME this Annotation information will be retained in the source file , the class file will be loaded into the JVM
 

very clear what we want to see RUNTIME dish , because we want to use Annotation to get some information, we also look at look at our built-in Annotation will belong to which it ? @ Override is used Retention (value = RetentionPolicy.SOURCE), @ Deprecated uses Retention (value = RetentionPolicy.RUNTIME), @ SuppressWarnings also used Retention (value = RetentionPolicy.SOURCE), summarize, one can really for us Annotation is functioning should be defined :

 
  
1 @Retention(value=RetentionPolicy.RUNTIME) 
2 public @interface MyAnnotation {
3
4 public String name() default "xujianguo";
5 public int age() default 20;
6 public String[] array();
7 public MyEnum system() default MyEnum.linux;
8 }
 
 

 

Annotation and Reflection :

 

Speaking Annotation application , you will not leave reflection , there is a class in the Class Annotation related to the operation with the following method : < / span>

                                                                                                                     
method Description
public Annotation > A getAnnotation ( Class annotationClass) if there is the element of the specified type annotation, the return of these comments, otherwise return null

public Annotation [] getAnnotations ()

present on this element returns all annotations
public Annotation [] getDeclaredAnnotations () return directly present on this element to all comments.
public boolean isAnnotation () determine whether the element represents a comment
public boolean isAnnotationPresent ( Class Annotation > annotationClass) If the specified types of comments present on this element , it returns true, otherwise returns false
 

Here I customize an Annotation, use this Annotation to mimic the JUnit @ Test annotation , and custom attributes also have this Annotation , to the value of this attribute out :

 

custom Annotation-TestSimulation:

 
  
1 @Retention(value=RetentionPolicy.RUNTIME) 
2 public @interface TestSimulation {
3 public String author() default "xujianguo";
4 }
 
 

use annotated classes AnnotationDemo class :

 
  
 1 public class AnnotationDemo { 
2
3 @TestSimulation(author="zhouyanping")
4 public void print() {
5 System.out.println("This is the method of print");
6 }
7
8 public void say() {
9 System.out.println("This is the method of say");
10 }
11
12 @TestSimulation
13 public void coding() {
14 System.out.println("This is the method of coding");
15 }
16 }
 
 

the reflection resolution AnnotationUtil class :

 
  
 1 public class AnnotationUtil { 
2
3 public static void main(String[] args) throws Exception {
4
5 /**
6 * 反射类的对象和拿出一个方法组
7 * @author Guo
8 */
9 Class clazz = Class.forName("com.xujianguo.test.AnnotationDemo");
10 Object object = clazz.newInstance();
11 Method[] methods = clazz.getMethods();
12
13 for(Method method : methods) {
14
15 /**
16 * 对方法上的注解进行核对
17 * @author Guo
18 */
19 if(method.isAnnotationPresent(TestSimulation.class)) {
20
21 /**
22 * 拿到指定的Annotation并获取相应的信息
23 * @author Guo
24 */
25 TestSimulation ts = method.getAnnotation(TestSimulation.class);
26 System.out.println(ts.author());
27 method.invoke(object);
28 }
29 }
30 }
31 }
 
 

 

没有评论:

发表评论