import java.lang.annotation.*; import static java.lang.annotation.ElementType.*; import static java.lang.annotation.ElementType.LOCAL_VARIABLE; @Inherited @Repeatable(MyAnnotations.class) @Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE, TYPE_PARAMETER, TYPE_USE}) @Retention(value = RetentionPolicy.RUNTIME) public @interface MyAnnotation { String value() default "hello"; }
说明:
import java.lang.annotation.*; import static java.lang.annotation.ElementType.*; import static java.lang.annotation.ElementType.LOCAL_VARIABLE; @Inherited @Documented @Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE, TYPE_PARAMETER, TYPE_USE}) @Retention(value = RetentionPolicy.RUNTIME) public @interface MyAnnotation { String value() default "hello"; }
6.1 可重复注解:
import java.lang.annotation.*; import static java.lang.annotation.ElementType.*; import static java.lang.annotation.ElementType.LOCAL_VARIABLE; @Inherited @Repeatable(MyAnnotations.class) @Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE, TYPE_PARAMETER, TYPE_USE}) @Retention(value = RetentionPolicy.RUNTIME) public @interface MyAnnotation { String value() default "hello"; }
import java.lang.annotation.Inherited; 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.LOCAL_VARIABLE; @Inherited @Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE}) @Retention(value = RetentionPolicy.RUNTIME) public @interface MyAnnotations { MyAnnotation[] value(); }
@MyAnnotation(value = "world") //jdk8 之前的写法 //@MyAnnotations({@MyAnnotation(value = "hello"),@MyAnnotation(value = "world")}) //jdk8 之后的写法 @MyAnnotation(value = "hello") @MyAnnotation(value = "world") class Person { private String name; private int age; public Person() { } public Person(String name, int age) { this.name = name; this.age = age; } public void walk() { System.out.println("人走路"); } public void eat() { System.out.println("人吃饭"); } }
6.2 类型注解:
import java.lang.annotation.*; import static java.lang.annotation.ElementType.*; import static java.lang.annotation.ElementType.LOCAL_VARIABLE; @Inherited @Repeatable(MyAnnotations.class) @Target({TYPE_PARAMETER, TYPE_USE}) @Retention(value = RetentionPolicy.RUNTIME) public @interface MyAnnotation { String value() default "hello"; }
class Generic<@MyAnnotation T> { public void show() throws @MyAnnotation RuntimeException{ ArrayList<@MyAnnotation String> list = new ArrayList<>(); int num = (@MyAnnotation int) 10L; } }