枚举类与注解8-可重复注解(JDK8新特性)

可重复注解

1、方法

1)在MyAnnotation上声明@Repeateble,成员值为MyAnnotations.class

2)MyAnnotation的Target和Rentention,要与MyAnnotations相同

要使用的地方

@MyAnnotation(value ="Morning")

@MyAnnotation(value ="Good Night")

//JDK8之前,多注解写法

//@MyAnnotations({@MyAnnotation(value = "hello"),@MyAnnotation(value = "Hi")})

class Person {

private Stringname;

private int age;

public Person(String name,int age) {

this.name = name;

this.age = age;

}

......

}

MyAnnotations.class

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;

@Retention(RetentionPolicy.RUNTIME)

@Target({TYPE,FIELD,METHOD,PARAMETER,CONSTRUCTOR,LOCAL_VARIABLE})

public @interface MyAnnotations {

    MyAnnotation[] value();

}

MyAnnotation.class

import java.lang.annotation.*;

import static java.lang.annotation.ElementType.*;

@Inherited

@Repeatable(MyAnnotations.class)

@Retention(RetentionPolicy.RUNTIME)

@Target({TYPE,FIELD,METHOD,PARAMETER,CONSTRUCTOR,LOCAL_VARIABLE})

public @interface MyAnnotation {

    String value()default "Hello";

}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容