创建注解MyAnnotion
@Repeatable(MyAnnotations.class)注解可以重复
package 新特性;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Repeatable(MyAnnotations.class)
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.CONSTRUCTOR, ElementType.LOCAL_VARIABLE,ElementType.TYPE_PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotion {
String value() default "www";
}
MyAnnotations 注解容器
package 新特性;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Repeatable(MyAnnotations.class)
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.CONSTRUCTOR, ElementType.LOCAL_VARIABLE,ElementType.TYPE_PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotion {
String value() default "www";
}
重复注解的使用
package 新特性;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import org.junit.Test;
/**
* 重复注解与类型注解
* @author wangqiangac
* @verion NCC-1.0
* @since 2021-10-13 14:50:35
*/
public class TestAnnotation {
//1.8还没有NonNull注解 需要配合框架checker framework 不允许为空,会在编译时报错
private /* @NonNull */ Object obj = null;
@Test
public void test() throws NoSuchMethodException, SecurityException {
Class<TestAnnotation> clazz = TestAnnotation.class;
Method m1 = clazz.getMethod("show", new Class<?>[] {String.class});
MyAnnotion[] annotations = m1.getAnnotationsByType(MyAnnotion.class);
for (MyAnnotion myAnnotion : annotations) {
System.out.println(myAnnotion.value());
}
Annotation[][] parameterAnnotations = m1.getParameterAnnotations();
for (Annotation[] annotations2 : parameterAnnotations) {
System.out.println(annotations2[0]);
MyAnnotion myAnnotion = (MyAnnotion) annotations2[0];
System.out.println(myAnnotion.value());
}
}
@MyAnnotion("hello")
@MyAnnotion("word")
public void show(@MyAnnotion("abc") String str) {
}
}