自定義一個註解
原理:
J2SE5.0版本在 java.lang.annotation提供了四種元註解,專門註解其他的註解:
@Documented –註解是否將包含在JavaDoc中
@Retention –什麼時候使用該註解
@Target? –註解用於什麼地方
@Inherited – 是否允許子類繼承該註解
@Documented–一個簡單的Annotations標記註解,表示是否將註解信息添加在java文檔中。
@Retention– 定義該註解的生命週期。
RetentionPolicy.SOURCE – 在編譯階段丟棄。這些註解在編譯結束之後就不再有任何意義,所以它們不會寫入字節碼。@Override, @SuppressWarnings都屬於這類註解。
RetentionPolicy.CLASS – 在類加載的時候丟棄。在字節碼文件的處理中有用。註解默認使用這種方式。
RetentionPolicy.RUNTIME– 始終不會丟棄,運行期也保留該註解,因此可以使用反射機制讀取該註解的信息。我們自定義的註解通常使用這種方式。
@Target – 表示該註解用於什麼地方。如果不明確指出,該註解可以放在任何地方。以下是一些可用的參數。需要說明的是:屬性的註解是兼容的,如果你想給7個屬性都添加註解,僅僅排除一個屬性,那麼你需要在定義target包含所有的屬性。
ElementType.TYPE:用於描述類、接口或enum聲明
ElementType.FIELD:用於描述實例變量
ElementType.METHOD
ElementType.PARAMETER
ElementType.CONSTRUCTOR
ElementType.LOCAL_VARIABLE
ElementType.ANNOTATION_TYPE 另一個註釋
ElementType.PACKAGE 用於記錄java文件的package信息
@Inherited – 定義該註釋和子類的關係
看代碼:
註解代碼:
/**
* 版權所有 (c) 2016,
*/
package helloTest.Annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 類說明:
*
* <pre>
* Modify Information:
* Author Date Description
* ============ =========== ============================
* wangxiaoming 2016-7-12 Create this file
* </pre>
*
*/
@Inherited
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAnnotation {
String value() default "你好";
}
引用註解的類:
/**
* 版權所有 (c) 2016,
*/
package helloTest.AnnotationTest;
import helloTest.Annotation.MyAnnotation;
/**
* 類說明:
*
* <pre>
* Modify Information:
* Author Date Description
* ============ =========== ============================
* wangxiaoming 2016-7-12 Create this file
* </pre>
*
*/
public class BussinessClass {
@MyAnnotation
private String value;
/**
* @return the value
*/
public String getValue() {
return value;
}
/**
* @param value the value to set
*/
public void setValue(String value) {
this.value = value;
}
}
註解是否生效測試:
/**
* 版權所有 (c) 2016
*/
package helloTest.AnnotationTest;
import helloTest.Annotation.MyAnnotation;
import java.lang.reflect.Field;
/**
* 類說明:
*
* <pre>
* Modify Information:
* Author Date Description
* ============ =========== ============================
* wangxiaoming 2016-7-12 Create this file
* </pre>
*
*/
public class AnnotationTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
BussinessClass bussinessClass = new BussinessClass();
/* try {
Field field = bussinessClass.getClass().getField("value");
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
Field[] fields = bussinessClass.getClass().getDeclaredFields();
for(Field f :fields ){
MyAnnotation annotation = f.getAnnotation(MyAnnotation.class);
System.out.println("name: "+f.getName()+" value: "+annotation.value());
}
}
}