Java8重复注解与类型注解

来源:互联网 发布:手机摄影师调色软件 编辑:程序博客网 时间:2024/06/06 16:30
Java8对注解处理提供了两点改进:可重复的注解及可用于类型的注解。
一、重复注解
package com.expgiga.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;/** * 自定义注解 */@Repeatable(MyAnnotations.class)@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})@Retention(RetentionPolicy.RUNTIME)public @interface MyAnnotation {    String value() default "expgiga";}

package com.expgiga.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;/** * 注解容器 */@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})@Retention(RetentionPolicy.RUNTIME)public @interface MyAnnotations {    MyAnnotation[] value();}

package com.expgiga.Java8;import java.lang.reflect.Method;/** * Java8重复注解与类型注解 */public class TestAnnotation {    public static void main(String[] args) throws NoSuchMethodException {       Class<TestAnnotation> clazz = TestAnnotation.class;       Method m1 = clazz.getMethod("show");       MyAnnotation[] mas = m1.getAnnotationsByType(MyAnnotation.class);       for (MyAnnotation myAnnotation : mas) {           System.out.println(myAnnotation.value());       }    }    @MyAnnotation("Hello")    @MyAnnotation("World")    public void show() {    }}

二、类型注解
package com.expgiga.Java8;import java.lang.annotation.*;import static java.lang.annotation.ElementType.*;import static java.lang.annotation.ElementType.CONSTRUCTOR;import static java.lang.annotation.ElementType.LOCAL_VARIABLE;/** * 自定义注解 */@Repeatable(MyAnnotations.class)@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE, TYPE_PARAMETER})@Retention(RetentionPolicy.RUNTIME)public @interface MyAnnotation {    String value() default "expgiga";}

package com.expgiga.Java8;import java.lang.reflect.Method;/** * Java8重复注解与类型注解 */public class TestAnnotation {    //checker framework    private /*@NotNull*/ Object obj = null;    public static void main(String[] args) throws NoSuchMethodException {       Class<TestAnnotation> clazz = TestAnnotation.class;       Method m1 = clazz.getMethod("show");       MyAnnotation[] mas = m1.getAnnotationsByType(MyAnnotation.class);       for (MyAnnotation myAnnotation : mas) {           System.out.println(myAnnotation.value());       }    }    @MyAnnotation("Hello")    @MyAnnotation("World")    public void show(@MyAnnotation("abc") String str) {    }}