场景
最近写一个文档, 用到了一个导出类的属性释义, 但这些释义定义在导出类属性上的注解上, 如下
几十个字段好几个类, 一个个敲是自然万万不可,复制也太慢, 最好是写个代码一锅端!
方案
此处用到了反射, 还有java.lang下的两个方法
- java.lang.Package.isAnnotationPresent(Class<? extends Annotation> annotationClass)
- 如果指定类型的注释存在于此元素上, 方法返回true
- java.lang.Package.getAnnotation(Class< A > annotationClass)
- 如果是该类型的注释, 方法返回该元素的该类型的注释
实例
实体类TestExportVO
import java.io.Serializable;
import java.lang.reflect.Field;
import cn.afterturn.easypoi.excel.annotation.Excel;
import io.swagger.annotations.ApiModel;
import lombok.Data;
@Data
@ApiModel(value = "TestExportVO")
public class TestExportVO implements Serializable {
private static final long serialVersionUID = 1L;
/** 姓名 */
@Excel(name = "姓名", width = 15)
private String studentName;
/** 身份证号 */
@Excel(name = "身份证号", width = 20)
private String identityId;
/** 学号 */
@Excel(name = "学号", width = 20)
private String studentId;
/** 出生日期 */
@Excel(name = "出生日期", width = 15)
private String birthday;
// ......
}
获取注释上的内容
public static void main(String[] args) {
// 获取类注解
if(TestExportVO.class.isAnnotationPresent(ApiModel.class)){
System.out.println(TestExportVO.class.getAnnotation(ApiModel.class).value());
}
// 获取类变量注解:
Field[] fields = TestExportVO.class.getDeclaredFields();
for (Field f : fields) {
if(f.isAnnotationPresent(Excel.class)){
System.out.print(f.getAnnotation(Excel.class).name() + ",");
}
}
}
运行如下
扩展
获取方法上的注解
// 获取方法注解:
Method[] methods = TestExportVO.class.getDeclaredMethods();
for (Method m : methods) {
if(m.isAnnotationPresent(Excel.class)){
System.out.println(m.getAnnotation(Excel.class).name());
}
}
获取方法参数上的注解
// 获取方法参数注解:
Method[] methods2 = TestExportVO.class.getDeclaredMethods();
for (Method m : methods2) {
// 获取方法的所有参数
Parameter[] parameters = m.getParameters();
for (Parameter p : parameters) {
// 判断是否存在注解
if(p.isAnnotationPresent(Excel.class)){
System.out.println(p.getAnnotation(Excel.class).name());
}
}
}