根据字段索引映射java对象工具类

前一段时间在公司做项目时遇到一个需求,我们的系统数据库基础数据都是从“中台系统推送过来”,我们系统通过定时跑批每次从“中台系统”读取txt文件,将txt文件映射成java对象然后入库,保持我系统与中台系统基础数据始终保持同步。

下面把相关工具类贴出来最为笔记分享给大家。

工具类有2套,一套是通过txt映射字段索引进行映射,另一套是根据字段属性名进行映射。两套工具都能用,但是我们最终确定的是根据索引来进行映射。

1.注解类

@

import java.lang.annotation.*;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface         {
     String tableName() default "";
     int index() default 0;
}

使用案例:

tableName:根据属性映射字段名

index:映射索引

2.TransBeanUtils将txt转换成bean工具类

import cn.hutool.core.util.StrUtil;
import com.hx.platform.dxjfgl.base.enums.SyncJobEnum;
import com.hx.platform.dxjfgl.sync.annos.Prop;
import com.hx.platform.dxjfgl.sync.model.People;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @author guxiang
 * @date 2022-1-10 14:44
 * @description txt根据字段索引转换bean工具类
 */
public class TransBeanUtils {

    public static <T> T getMappingPo(Class<T> classz, Object[] objs) throws Exception {
        Field[] fields = classz.getDeclaredFields();
        Object object = classz.newInstance();
        int length = objs.length;

        for (Field fild : fields) {
            String typeStr = fild.getType().getSimpleName().toLowerCase();
            Annotation[] annos = fild.getAnnotations();

            if (annos.length > 0) {
                for (Annotation anno : annos) {
                    if (("Prop".equals(anno.annotationType().getSimpleName()))) {
                        Prop myAmoncation = (Prop) anno;
                        int index = myAmoncation.index();

                        if (index < length) {
                            fild.setAccessible(true);
                            Object value;
                            if ("double".equals(typeStr)) {
                                value = Double.valueOf(objs[index] == null ? "0" : objs[index].toString().trim());
                            } else if ("int".equals(typeStr) || "integer".equals(typeStr)) {
                                value = Integer.valueOf(objs[index] == null ? "0" : objs[index].toString().trim());
                            } else if ("float".equals(typeStr)) {
                                value = Float.valueOf(objs[index] == null ? "0" : objs[index].toString().trim());
                            } else if ("long".equals(typeStr)) {
                                value = Long.valueOf(objs[index] == null ? "0" : objs[index].toString().trim());
                            } else if ("date".equals(typeStr)) {
                                String dateStr = objs[index].toString().trim();
                                if (StrUtil.isBlank(dateStr) || StrUtil.equalsIgnoreCase("null", dateStr)) {
                                    value = null;
                                }
                                value = String.valueOf(dateStr);
                            } else if ("bigdecimal".equals(typeStr)) {
                                String s = objs[index].toString().trim();
                                long l = s.equals("null")||s.equals("NULL") || s.equals("") ? 0l : Long.parseLong(s);
                                value = BigDecimal.valueOf(l);
                            } else {
                                value = String.valueOf(objs[index]).trim();
                            }
                            if (value != null && StrUtil.equalsIgnoreCase("null", value.toString().trim())) {
                                value = null;
                            }
                            fild.set(object, value);
                        }
                    }
                }
            }
        }
        return (T) object;
    }

    /**
     * @author guxiang
     * @date 2022-1-10 11:04
     * @description 解析Txt文件
     */
    public static <T> List<T> resolverTxt(String tmpPath, SyncJobEnum e) throws Exception {
        File file = new File(tmpPath);
        boolean exists = file.exists();
        if (!exists) {
            throw new Exception("文件不存在");
        }
        Class<T> clazz = (Class<T>) Class.forName(e.getTargetClassPath());
        try(BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));) {
            List<T> beans = new ArrayList<>();
            String tempString;
            int line = 1;
            while ((tempString = reader.readLine()) != null) {
                if (tempString.contains("-+-")) {
                    continue;
                }
                String[] split = tempString.split("\\|");
                T bean = TransBeanUtils.getMappingPo(clazz, split);

                beans.add(bean);
                line++;
            }
            return beans;
        }
    }

    /**
     * @author guxiang
     * @date 2022-1-13 9:14
     * @description 根据索引映射字段
     */
    public static void main(String[] args) throws Exception {
        String tmpPath = "C:\\Users\\Administrator\\Desktop\\数据机房\\testindex.txt";
        List<People> peoples = resolverTxt(tmpPath, SyncJobEnum.TEST);
        for (People people : peoples) {
            System.out.println(people);
        }

    }

}

3.SyncJobEnum枚举类

用于配置需要转换对象的相对位置,工具类中会用到反射,所以要配置需要转换java对象的相对位置

/**
 * @author guxiang
 * @date 2022-1-12 19:24
 * @description 机房数据同步枚举类
 */
public enum SyncJobEnum {

    TEST("TEST", "com.hx.platform.dxjfgl.sync.test.Person", "com.hx.platform.dxjfgl.sync.test.People", "测试枚举"),

    /**
     * 区域子区域信息
     */
    AREA("AREA", "", "com.hx.platform.dxjfgl.sync.area.BaseRegionSync", "区域子区域信息"),

    /**
     * 站点信息
     */
    SITE("SITE", "", "com.hx.platform.dxjfgl.sync.site.BaseStationSync", "站点信息"),

    /**
     * 机架信息
     */
    HOLDER("HOLDER", "", "com.hx.platform.dxjfgl.sync.holder.BaseJginfoSync", "机架信息"),

    /**
     * 设备信息
     */
    NODE("NODE", "", "com.hx.platform.dxjfgl.sync.node.BaseItdeviceSync", "设备信息"),

    /**
     * 机楼信息
     */
    BUILD("BUILD", "", "com.hx.platform.dxjfgl.sync.build.BaseBuildingsSync", "机楼信息"),
    /**
     * 机房信息
     */
    JF_INFO("JF_INFO", "", "com.hx.platform.dxjfgl.sync.model.JfInfo", "机房信息"),
    /**
     * 视频设备"
     */
    VIDEO("VIDEO", "", "com.hx.platform.dxjfgl.sync.model.Video", "视频设备"),
    /**
     * 门禁设备
     */
    ENTRANCE("ENTRANCE", "", "com.hx.platform.dxjfgl.sync.model.Entrance", "门禁设备"),
    /**
     * IT设备
     */
    IT_DEVICE("IT_DEVICE", "", "com.hx.platform.dxjfgl.sync.model.ItDevice", "IT设备"),
    /**
     * 组织机构
     */
    ORG("ORG", "", "com.hx.platform.dxjfgl.sync.org.BaseOrgSycnTmp", "电信组织机构"),
    /**
     * 人员信息
     */
    STAFF("STAFF", "", "com.hx.platform.dxjfgl.sync.staff.BaseStaffSycnTmp", "人员信息"),
    /**
     * 门禁信息
     */
    ENTRANCETMP("ENTRANCETMP", "", "com.hx.platform.dxjfgl.entrance.model.BaseEntranceinfoSycnTmp", "门禁信息"),
    /**
     * 门禁出入历史记录
     */
    ENTRANCEHIS("ENTRANCEHIS", "", "com.hx.platform.dxjfgl.entrance.model.EntranceAccessHis", "门禁出入历史记录");

    /**
     * 值 String型
     */
    private final String value;

    /**
     * 原对象路径
     */
    private final String originClassPath;

    /**
     * 目标对象路径
     */
    private final String targetClassPath;

    /**
     * 描述 String型
     */
    private final String description;

    SyncJobEnum(String value, String originClassPath, String targetClassPath, String description) {
        this.value = value;
        this.originClassPath = originClassPath;
        this.targetClassPath = targetClassPath;
        this.description = description;
    }

    public String getValue() {
        return value;
    }

    public String getOriginClassPath() {
        return originClassPath;
    }

    public String getTargetClassPath() {
        return targetClassPath;
    }

    public String getDescription() {
        return description;
    }
}

4.使用案例

5.工具类源码贴在这个链接里,自行下载

免积分免费用纯分享!

txt根据索引转换对象工具类-Java文档类资源-CSDN下载

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值