使用自定义注解主要分为三个步骤:
自定义注解,使用元注解对自定义注解进行设置,反射注解
1.自定义注解
public @interface ManyMemberAnnoations{
String describle();
Class type();
}
在定义Annoation类型时,需要用到用来定义接口的interface关键字,但需要在interface前面加一个@的符号,此关键字的隐含意思就是继承了java.lang.annoation.Annoation接口
2.使用元注解对自定义注解进行设置
使用元注解对自定义注解进行设置,Java的元注解位于java.lang.annoation包下,主要负责用来注解其他的注解。
Java中共有4个元注解
1)@Documented:指示某一类型的注释通过javadoc和类似的默认工具进行文档化
2)@Inherited: 指示注解类型被自动继承
3)@Retention: 指示注解类型的注释要保留多久
4)@Target 指示注解类型所适用元素的种类
常用Retention和Target注解
Target注解中有如下成员
Retention中有如下注解
SOURCE表示不编译Annoation到文件中,有效范围小
CLASS表示编译Annoation到类文件中,但是在运行时不加载Annoation到JVM中
RUNTIME 表示在运行过程时加载Annoation到JVM中,有效范围大
样例如下
package com.zhicheng;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface PhoneAnnotation {
public String remarks() default "";
public boolean enable() default true;
}
package com.zhicheng;
public class CellPhone {
@PhoneAnnotation(remarks="品牌型号")
public String brdMl;
@PhoneAnnotation(remarks="价格")
public double price;
@Deprecated
@PhoneAnnotation(remarks="电池接口", enable=false)
public String batteryInter;
@PhoneAnnotation(remarks="手机厂商")
String producedArea;
}
package com.zhicheng;
import java.lang.reflect.Field;
public class Test {
public static void main(String[] args) {
Class c = CellPhone.class;
Field [] fields = c.getDeclaredFields();
for (Field field : fields) {
if (field.isAnnotationPresent(PhoneAnnotation.class)) {
PhoneAnnotation phoneAnnotation = field.getAnnotation(PhoneAnnotation.class);
System.out.println(field.getName()+" 备注:"+phoneAnnotation.remarks()+" 属性 "+phoneAnnotation.enable());
}
}
}
}