1、总结
1、忘记注解上该写什么时,可以随意写一个注解然后点击进去参考、复制
2、默认情况下不支持重复注解,需要定义容器
3、标注注解为@Repeatable
4、若需要获取注解的值,可以通过反射获取
2、源码
TestAnnotation
package com.atguigu.java8;
import org.junit.Test;
import java.lang.reflect.Method;
/**
* @author wertherwang
* @create 2019-09-26 15:41
*/
public class TestAnnotation {
@Test
public void test1() throws NoSuchMethodException {
Class clazz = TestAnnotation.class;
Method show = clazz.getMethod("show");
MyAnnotation[] mas = show.getAnnotationsByType(MyAnnotation.class);
for (MyAnnotation myAnnotation : mas) {
System.out.println(myAnnotation.value());
}
}
@MyAnnotation("Hello")
@MyAnnotation("World")
private void show() {
}
}
MyAnnotation
package com.atguigu.java8;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.LOCAL_VARIABLE;
/**
* @author wertherwang
* @create 2019-09-26 15:35
*/
@Repeatable(MyAnnotations.class)
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.SOURCE)
public @interface MyAnnotation {
String value() default "atguigu";
}
MyAnnotations
package com.atguigu.java8;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.LOCAL_VARIABLE;
/**
* @author wertherwang
* @create 2019-09-26 15:39
*/
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.SOURCE)
public @interface MyAnnotations {
MyAnnotation[] value();
}