代码实例
package com.guor.ClientNew;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)//注解可以保留到程序运行时,加载到JVM中
@Target(ElementType.TYPE)//给一个类型进行注解,比如类、接口、枚举
@Inherited //子类继承父类时,注解会起作用
public @interface Desc {
enum Color {
White, Grayish, Yellow
}
// 默认颜色是白色的
Color c() default Color.White;
}
5、@Repeatable
Repeatable 自然是可重复的意思。@Repeatable 是 Java 1.8 才加进来的,所以算是一个新的特性。
什么样的注解会多次应用呢?通常是注解的值可以同时取多个。
在生活中一个人往往是具有多种身份,如果我把每种身份当成一种注解该如何使用???
先声明一个Persons类用来包含所有的身份
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Persons {
Person[] value();
}
这里@Target是声明Persons注解的作用范围,参数ElementType.Type代表可以给一个类型进行注解,比如类,接口,枚举。
@Retention是注解的有效时间,RetentionPolicy.RUNTIME是指程序运行的时候。
Person注解:
@Repeatable(Persons.class)
public @interface Person{
String role() default “”;
}
@Repeatable括号内的就相当于用来保存该注解内容的容器。
声明一个Man类,给该类加上一些身份。
@Person(role=“CEO”)
@Person(role=“husband”)
@Person(role=“father”)
@Person(role=“son”)
public class Man {
String name=“”;
}
在主方法中访问该注解:
public static void main(String[] args) {
Annotation[] annotations = Man.class.getAnnotations();
System.out.println(annotations.length);
Persons p1=(Persons) annotations[0];
for(Person t:p1.value()){
System.out.println(t.role());
}
}
下面的代码结果输出相同,但是可以先判断是否是相应的注解,比较严谨。
if(Man.class.isAnnotationPresent(Persons.class)) {
Persons p2=Man.class.getAnnotation(Persons.class);
for(Person t:p2.value()){
System.out.println(t.role());
}
}
运行结果:
四、注解的属性
注解的属性也叫做成员变量,注解只有成员变量,没有方法。注解的成员变量在注解的定义中以“无参的方法”形式来声明,其方法名定义了该成员变量的名字,其返回值定义了该成员变量的类型。
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.