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


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;
    }
}
  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这是一个技术问题,我可以为您提供一些信息。在Java中,要获取注解信息可以使用反射机制。首先需要获取类的Class对象,然后通过这个对象获取到指定方法或字段上的注解对象。可以使用Annotation接口的实现类来获取注解信息,再使用反射机制修改注解的内容。下面是一个简单的示例代码: ```java // 定义一个注解类 @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface MyAnnotation { String value() default "原始"; } // 在方法上使用注解 public class MyClass { @MyAnnotation("Hello, World!") public void myMethod() { System.out.println("My method."); } } // 反射获取注解并修改内容 Class myClass = MyClass.class; Method myMethod = myClass.getMethod("myMethod"); MyAnnotation myAnnotation = myMethod.getAnnotation(MyAnnotation.class); String oldValue = myAnnotation.value(); System.out.println("原始:" + oldValue); // 修改注解内容 MyAnnotation newAnnotation = new MyAnnotation() { public String value() { return "新"; } public Class<? extends Annotation> annotationType() { return MyAnnotation.class; } }; Method method = myClass.getDeclaredMethod("myMethod"); // 获取该方法上的注解 Annotation annotation = method.getAnnotation(MyAnnotation.class); // 获取 AnnotationInvocationHandler 实例 InvocationHandler invocationHandler = Proxy.getInvocationHandler(annotation); // 获取 memberValues 字段 Field memberValues = invocationHandler.getClass().getDeclaredField("memberValues"); // 取消 Java 语言访问检查以访问私有字段 memberValues.setAccessible(true); // 修改注解 Map<String, String> values = (Map<String, String>) memberValues.get(invocationHandler); values.put("value", newAnnotation.value()); String newValue = myMethod.getAnnotation(MyAnnotation.class).value(); System.out.println("新:" + newValue); ``` 上述代码示例中,我们定义了一个名为“MyAnnotation”的注解,并在MyClass类的myMethod()方法上使用了该注解。然后,我们使用反射机制获取myMethod()方法上的注解对象,并修改了注解的内容。最后,我们再次获取注解对象的内容,验证注解内容已被修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值