java实现实体类转定长报文

创建注解

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface LeftWithSpace {
    int len() default 0;
}

创建实体类

@Data
public class LeftWithSpaceDto {
    @LeftWithSpace(len = 10)
    private String a;
    
    @LeftWithSpace(len = 20)
    private String b;
}

实现


public class LeftWithSpaceService {
    public static String leftMethod(Object obj, Class<?> claz) throws Exception {
        Field[] fields = claz.getDeclaredFields();
        StringBuilder sb = new StringBuilder();
        for (Field field : fields) {
            if (field.isAnnotationPresent(LeftWithSpace.class)) {
                LeftWithSpace annotation = field.getAnnotation(LeftWithSpace.class);
                int len = annotation.len();
                field.setAccessible(true);
                if (Objects.isNull(field.get(obj))) {
                    sb.append(leftWithSpaces("", len));
                } else {
                    String str = field.get(obj).toString();
                    int length = StrUtil.bytes(str, "GBK").length;
                    if (length < len) {
                        sb.append(leftWithSpaces(str, len));
                    } else {
                        throw new RuntimeException("字段超长");
                    }
                }
                field.setAccessible(false);
            }
            field.setAccessible(true);
            if (!Objects.isNull(field.get(obj))) {
                sb.append(leftMethod(field.get(obj), field.get(obj).getClass()));
            }
            field.setAccessible(false);

        }
        return sb.toString();
    }

    private static String leftWithSpaces(String str, int len) {
        if (StrUtil.isEmpty(str)) {
            return StrUtil.fillAfter("", ' ', len);
        }
        int length = StrUtil.bytes(str, "GBK").length;
        int strLen = str.length();
        if (length == strLen) {
            return StrUtil.fillAfter(str, ' ', len);
        } else {
            int i = length - strLen;
            return StrUtil.fillAfter(str, ' ', len - i);
        }

    }

使用到的依赖

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.8</version>
        </dependency>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值