JavaSE元注解
在注解定義時(shí),用在注解頭部的注解,稱為元注解,目前元注解在java.lang.annotation包內(nèi),分別@Target,@Retention,@Documented,@Inherited,@Repeatable,@Native
@Documented
當(dāng)一個(gè)注解上面有此注解時(shí),使用此注解的方法等在生成Doc時(shí),Doc中會(huì)包含此注解,舉例如下
實(shí)驗(yàn)用注解:
@Documented
@Target(ElementType.TYPE)
@interface Version {
String value();
}
測(cè)試類:
@Version("1.0")
public class TestCase {
}
生成的文檔中
taste.annotations.meta.documented
類 TestCase
java.lang.Object
taste.annotations.meta.documented.TestCase
@Version(value="1.0") <<注解會(huì)被包含在文檔中
public class TestCase
extends java.lang.Object
@Inherited
注解被用在類聲明上時(shí),可以使用此注解,被這類注解修飾的類,子類與父類有相同的注解
比如
@Inherited @interface Persistent { }
@Persistent class Employee { . . . }
class Manager extends Employee { . . . } // <==這個(gè)類,也有Persitent注解
類Manager同樣有@Persistent注解,也即一個(gè)類是可持久化的,那他的子類也是可持久化的,類似的例子還有@Serializable,但由于這個(gè)特性是在JDK1.1推出的,早于注解出現(xiàn)前,因此沒(méi)有用注解的形式
@Repeatable
注解被指定為@Repeatable時(shí),注解可以在同一個(gè)位置多次實(shí)現(xiàn),但定義此注解時(shí),需要同時(shí)定義一個(gè)容器注解,來(lái)包括重復(fù)的注解類,
知識(shí)要點(diǎn)
- 容器注解必須有一個(gè)名為value,類型為包裹注解數(shù)組的變量,且其他變量必須有默認(rèn)值
- 獲取注解時(shí),若注解確實(shí)是多次定義,則調(diào)用getAnnotation(.class)方法返回null,實(shí)際使用時(shí),若需處理可重復(fù)注解,請(qǐng)使用getDeclaredAnnotationsByType(.class)方法,返回的是對(duì)應(yīng)注解實(shí)例的數(shù)組
舉例:
定義可重復(fù)注解:
@Repeatable(InfoArray.class)
@Retention(RetentionPolicy.RUNTIME)
@interface Info {
String value();
}
定義包裹的注解
@Retention(RetentionPolicy.RUNTIME)
@interface InfoArray {
Info[] value();
String desc() default "a";
}
使用注解:
@Info("Created by kk")
@Info("On 2019/4/13")
public class TestCase {
}
獲取注解:
public static void main(String[] args) {
Class<TestCase> testCaseClass = TestCase.class;
Info infoAnnotation = testCaseClass.getAnnotation(Info.class);
System.out.println(infoAnnotation);
Info[] infoArray = testCaseClass.getDeclaredAnnotationsByType(Info.class);
for (Info info : infoArray) {
System.out.println(info.value());
}
}
輸出
null
Created by kk
On 2019/4/13
JavaEE原生注解
@SuppressWarnings("unchecked")
忽略某些Warning
@Override
表明某方法是復(fù)寫(xiě)父類方法
@Generated
表明此代碼為自動(dòng)生成,用來(lái)給IDE提供標(biāo)識(shí)以隱藏默寫(xiě)代碼,或者給代碼生成工具提供標(biāo)識(shí)以替換,有三個(gè)Field,典型用法:
@Generated(value = "com.kkyeer.taste",date = "2019-01-04T12:00:00",comment = "some comment")
@PostConstruct和PreDestroy
分別注解在實(shí)例初始化后和銷毀前執(zhí)行的方法
注意,這兩個(gè)注解本身并不提供這兩個(gè)功能,需要配合相關(guān)框架或者處理類才能發(fā)揮效果
@Resource
表明注解的變量由容器注入