自定义注解
package com.xxx.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.math.BigDecimal;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface AnnotationA {
/**
* varietyA
*
* @return
*/
String memberA() default "value";
}
1. @interface:注解定义
2. @Target:限定自定义注解可以在哪些元素上使用
ElementType.TYPE | 用于描述类、接口(包括注解类型) 或enum声明 Class, interface (including annotation type), or enum declaration |
ElementType.FIELD | 用于描述域 Field declaration (includes enum constants) |
3. @Retention:限定自定义注解的生命周期
RetentionPolicy.RUNTIME | 运行期阶段 Annotations are to be recorded in the class file by the compiler and retained by the VM at run time, so they may be read reflectively. |
RetentionPolicy.CLASS | 编译到class文件阶段(默认) Annotations are to be recorded in the class file by the compiler |
RetentionPolicy.SOURCE | JAVA源文件阶段 Annotations are to be discarded by the compiler. |
3. 自定义注解中定义成员变量的规则:
- 定义是以无形参的方法形式声明的
- 注解方法不带参数
- 注解方法返回值参数:基本类型、String、Enums、Annotation 以上及其数组类型
- 注解方法可有默认值 default "value"
引用注解
package cn.xxx.dto;
import cn.xxx.annotation.AnnotationA;
public class DtoA {
@ExampleA(memberA = "valueB")
private String planName;
}
获取注解的值
package cn.superfw.biz.platform.poi.factory;
import cn.superfw.biz.platform.annotation.ExcelImportField;
import cn.superfw.biz.platform.poi.entity.ExcelEntity;
import cn.superfw.biz.platform.poi.entity.ExcelPropertyEntity;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
public class ExcelMappingFactory {
public void getAnnotationValue(){
Class classA = DtoA.class;
// 获取类的所有域
Field[] fields = classA.getDeclaredFields();
for (Field field:fields){
// 获取域的指定注解
AnnotationA annotationA = field.getAnnotation(AnnotationA.class);
if ( null != annotationA ){
// 获取注解的值
String memberValue = annotationA.memberA();
}
}
}
}