jdk8新特性——其他特性

重複註解的使用

允許在同一個地方多次使用同一註解,jdk8使用@Repeatable註解定義重複註解

1。定義重複的註解容器註解

//定義重複的註解容器註解@Retention(RetentionPolicy。RUNTIME)public @interface MyTests { MyTest[] value();}

2。定義一個可以重複的註解

//定義一個可以重複的註解@Retention(RetentionPolicy。RUNTIME)@Repeatable(MyTests。class)public @interface MyTest { String value();}

3。配置多個重複的註解

@Test@MyTest(“ma”)@MyTest(“mb”)public void test(){}

4。解析得到指定註解

public static void main(String[] args) throws NoSuchMethodException { //解析重複註解 //getAnnotationsByType用於獲取重複註解 //獲取類上面的註解 MyTest[] annotationsByType = ZhujieDemo。class。getAnnotationsByType(MyTest。class); for (int i = 0; i < annotationsByType。length; i++) { System。out。println(annotationsByType[i]); } //獲取方法上的重複註解 MyTest[] tests = ZhujieDemo。class。getMethod(“test”)。getAnnotationsByType(MyTest。class); for (int i = 0; i < tests。length; i++) { System。out。println(tests[i]); }}

型別註解的使用

jdk8為@Target元註解新增了兩種型別:TYPE_PARAMETER、TYPE_USE

TYPE_PARAMETER:表示該註解能寫在型別引數的宣告語句中

TYPE_USE:表示註解可以在任何用到型別的地方使用

public class ZhujieDemo2 <@TypeParam T>{ public <@TypeParam E extends Integer> void test(){ }}@Target(ElementType。TYPE_PARAMETER)@interface TypeParam {}

public class ZhujieDemo3 { private @NotNull int a =10;}@Target(ElementType。TYPE_USE)@interface NotNull{}