Java反射获取实例并填充注解值

发布时间:2024年01月08日


1.场景

下载导入模版

2.普通实现方式

实现很简单,看着不那么优雅

  @GetMapping("/export-detail-template")
    @Operation(summary = "导出订单需求单明细导入模版 Excel")
    @OperateLog(type = EXPORT)
    public void exportTemplate(HttpServletResponse response) throws IOException {
        final DemandDetailImportTemplateVO templateVO = new DemandDetailImportTemplateVO();
        templateVO.setSeq(1);
        templateVO.setCustomerName("黄金大爷");
        templateVO.setSaleMan("张三");
        templateVO.setSkuNo("ES01BC0010");
        templateVO.setProductName("福叠(蝴蝶)");
        templateVO.setCategoryName("耳饰");
        templateVO.setBaseWeight("50");
        templateVO.setWeightSpan("40-50");
        templateVO.setNum(3);
        templateVO.setQualityRequired("足金999");
        templateVO.setPrintContent("无");
        templateVO.setCreateTime("2023/1/7  15:12:13");
        templateVO.setTimeRequired("2023/2/7  15:12:13");
        templateVO.setGuessWeight("49.99");
        templateVO.setRemark("无备注");
        ExcelUtils.write(response, "订单需求单明细导入模版.xls", "数据",
                DemandDetailImportTemplateVO.class,
                Collections.singletonList(templateVO));
    }

3. 利用反射+注解设置值方式

3.1 业务代码

@GetMapping("/export-detail-template")
    @Operation(summary = "导出订单需求单明细导入模版 Excel")
    @OperateLog(type = EXPORT)
    public void exportTemplate(HttpServletResponse response) {
        try {
            ExcelUtils.write(response, "订单需求单明细导入模版.xls", "数据", 
            DemandDetailImportTemplateVO.class,
                    Collections.singletonList(ReflUtil.getInstanceFillAnnotationValue(DemandDetailImportTemplateVO.class)));
        } catch (Exception e) {
            log.error("下载导入模版异常::" + e.getMessage());
            throw new ServiceException("下载导入模版异常");
        }
    }

3.2 业务实体

@Data
@Builder
@Accessors(chain = false)
public class DemandOrderImportVO {
    @ExcelIgnore
    private Integer req;

    @ExcelProperty("客户名称")
    @Schema(description = "客户名称", example = "黄金大爷")
    private String customerName;

    @ExcelProperty("业务")
    @Schema(description = "业务", example = "张三")
    private String saleMan;

    @ExcelProperty("款式编码")
    @Schema(description = "款式编码", example = "ES01BC0010")
    private String skuNo;

    @ExcelProperty("产品图片")
    @Schema(description = "产品图片")
    private URL imageUrl;

    @ExcelProperty("产品名称")
    @Schema(description = "产品名称", example = "福叠(蝴蝶)")
    private String productName;

    @ExcelProperty("品类")
    @Schema(description = "品类", example = "耳饰")
    private String categoryName;

    @ExcelProperty("样板克重")
    @Schema(description = "样板克重", example = "50")
    private String baseWeight;

    @ExcelProperty("克重范围")
    @Schema(description = "克重范围", example = "40-50")
    private String weightSpan;

    @ExcelProperty("件数")
    @Schema(description = "件数", example = "3")
    private Integer num;

    @ExcelProperty("成色要求")
    @Schema(description = "成色要求", example = "足金999")
    private String qualityRequired;

    @ExcelProperty("字印要求")
    @Schema(description = "字印要求", example = "无")
    private String printContent;

    @ExcelProperty("下单时间")
    @Schema(description = "下单时间", example = "2023/1/7  15:12:13")
    private String createTime;

    @ExcelProperty("交期要求")
    @Schema(description = "交期要求", example = "2023/2/7  15:12:13")
    private String timeRequired;

    @ExcelProperty("预估克重")
    @Schema(description = "预估克重", example = "49.99")
    private String guessWeight;

    @ExcelProperty("备注")
    @Schema(description = "备注", example = "无备注")
    private String remark;
}

3.3 工具方法

注意:目前值考虑了 Integer与string的字段对象

public class ReflUtil extends ReflectUtil {

    /**
     * 反射获取对象并根据Schema注解的example进行值填充
     *
     * @param tClass
     * @param <T>
     * @return
     * @throws Exception
     */
    public static <T> T getInstanceFillAnnotationValue(Class<T> tClass) throws Exception {
        final T instance = tClass.newInstance();
        final Field[] fields = ReflectUtil.getFields(tClass);
        for (final Field field : fields) {
            final Class<?> filedType = field.getType();
            if (filedType != Integer.class && filedType != String.class) {
                continue;
            }
            final Schema annotation = field.getAnnotation(Schema.class);
            if (ObjUtil.isNull(annotation)) {
                continue;
            }
            final String example = annotation.example();
            field.setAccessible(true);
            field.set(instance, filedType == Integer.class ? Integer.valueOf(example) : example);
        }
        return instance;
    }
}
文章来源:https://blog.csdn.net/User_bie/article/details/135462629
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。