1 什麼是annotationjava
annotation是java編譯器支持的一種標記,它能夠簡化咱們的代碼,使得咱們的代碼更加方便被理解。網絡
2 元annotationspa
用來編寫其它註解的註解。code
@Retentionorm
保留期,有三種保留期。繼承
RetentionPolicy.SOURCEget
這樣的註解只在源碼階段保留,編譯器在編譯的時候會忽略掉它們。編譯器
RetentionPolicy.CLASS源碼
編譯的時候會用到它們,可是不會加載到虛擬機中。虛擬機
RetentionPolicy.RUNTIME
保留到程序運行的時候,而且加載到虛擬機中,在程序運行的時候能夠經過反射獲取它們。
@Documented
將註解中的元素加載到javadoc中去。
@Target
指的是註解能夠生效的地方,有8種。ElementType.ANNOTATION_TYPE、ElementType.CONSTRUCTOR、ElementType.FIELD、ElementType.LOCAL_VARIABLE、
ElementType.METHOD、ElementType.PACKAGE、ElementType.PARAMETER、ElemenType.TYPE。
@Inherited
指的是子類繼承超類的註解。
@Repeatable
能夠屢次使用。
3 註解定義的通常形式
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation {
int id();
String msg();
}
4 帶成員變量的註解
4.1 定義帶成員變量的註解:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyTag {
// 定義兩個成員變量,註解的成員變量的定義以方法的形式來定義。
String name();
int age default 32;
}
4.2 帶成員變量的註解的使用
public class Test {
@MyTag(name = "Dhello")
public void info(){}
}
5 註解的提取和使用
5.1 使用的技術
反射。
5.2 判斷是否使用了註解
public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {}
5.3 獲取指定的註解
public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {}
5.4 獲取全部的註解
public Annotation[] getAnnotations() {}
4.5 使用案例
以下例子所示,咱們能夠獲取類上的註解、方法上的註解以及類的成員變量上的註解(該例子來自於網絡)。
@TestAnnotation(msg="hello") public class Test { @Check(value="hi") int a; @Perform public void testMethod(){} @SuppressWarnings("deprecation") public void test1(){ Hero hero = new Hero(); hero.say(); hero.speak(); } public static void main(String[] args) { boolean hasAnnotation = Test.class.isAnnotationPresent(TestAnnotation.class); if ( hasAnnotation ) { TestAnnotation testAnnotation = Test.class.getAnnotation(TestAnnotation.class); //獲取類的註解 System.out.println("id:"+testAnnotation.id()); System.out.println("msg:"+testAnnotation.msg()); } try { Field a = Test.class.getDeclaredField("a"); a.setAccessible(true); //獲取一個成員變量上的註解 Check check = a.getAnnotation(Check.class); if ( check != null ) { System.out.println("check value:"+check.value()); } Method testMethod = Test.class.getDeclaredMethod("testMethod"); if ( testMethod != null ) { // 獲取方法中的註解 Annotation[] ans = testMethod.getAnnotations(); for( int i = 0;i < ans.length;i++) { System.out.println("method testMethod annotation:"+ans[i].annotationType().getSimpleName()); } } } catch (NoSuchFieldException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println(e.getMessage()); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println(e.getMessage()); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println(e.getMessage()); } }