java通过反射给类变量赋值

项目需求

读取csv文件后,第一行的变量是一个字符串,中间用"╪"隔开,由于文件中变量(列)太多,而且好多变量是不需要的,这时候提取需要的变量就非常麻烦,如果人工去确定变量的位置非常麻烦,自己去定位1,3,13,23,45,头大。于是就想到通过变量明名称(列名称)去,自动匹配,获取定位然后给类赋值就可以了。

实现过程

读取数据

将数据读取到list集合中,list,get(0)就是第一行,代表各列的名称(变量名称),后面的就是数据。

ublic class CSVUtils {
    public static List<String[]> readExcel(String filePath)
    {
        List<String[]> communitys = new ArrayList<>();
        BufferedReader br = null;
        String line = "";
        String cvsSplitBy = "╪";
        try {
            DataInputStream in = new DataInputStream(new FileInputStream(new File(filePath)));
            br = new BufferedReader(new InputStreamReader(in,"utf-8"));
            line = br.readLine();
            while (line != null) {
                String[] community = line.split(cvsSplitBy);
                communitys.add(community);
                line = br.readLine();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return communitys;
    }
}

反射定位

通过反射获取类变量名称,然后与文件中变量比较,最后放在map集合中,key是变量名称,value是变量在数组arr中的位置。arr是文件中变量

public static Map<String,Integer> fieldPositioning (String[] arr){
        Map<String,Integer> map = new HashMap<>();
        for (int i = 0; i < arr.length; i++) {
            for (Field field: Community.class.getDeclaredFields()){
                if(field.getName().equals(arr[i]))
                {
                    map.put(field.getName(),i);
                    System.out.println(field.getName()+","+i);
                }
            }
        }
        return map;
    }

赋值

这里通过反射对类中的变量进行赋值

public static void main(String[] args) {
        String file = "D://ProcessFiles/community_www-soufang-com_web_2021-09-16_1.csv";
        //String file = "D://ProcessFiles/555.csv";
        try {
            initDao();
            List<String[]> communitys = CSVUtils.readExcel(file);
            ResidentialArea residentialArea = null;
            Map<String,Integer> map = fieldPositioning(communitys.get(0));
            if(map.size()==Community.class.getDeclaredFields().length) {
                System.out.println(true);
                for (int i = 1; i < communitys.size(); i++) {
                    String[] communityByFile = communitys.get(i);
                    Community community = new Community();
                    Set<Map.Entry<String,Integer>> entrySet = map.entrySet();
                    for (Map.Entry<String, Integer> entry : entrySet) {
                        String key = entry.getKey();
                        String value = communityByFile[entry.getValue()];
                        //System.out.println(key+","+value);
                        if(value!=null&&!value.equals("")){
                            Field field = community.getClass().getDeclaredField(key);
                            Object object = TypeConversionUtils.TypeConversion(field, value);
                            community.getClass().getDeclaredField(key).set(community,object);
                        }
                    }
                    logger.info(community.toString());
                    
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

这里因为变量的类型都不一样所以我进行了转换。

public static Object TypeConversion(Field field,String value){
        Object object =new Object();
        if(field.getType()==new String().getClass()){
            object = value;
        }else if(field.getType()==new Double(1.1).getClass()){
            object = Double.valueOf(value);
        }else if(field.getType()==new Date().getClass()){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if(value.length()==4){
                sdf = new SimpleDateFormat("yyyy");
            }
            try {
                object = sdf.parse(value);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }else if(field.getType()==new Integer(0).getClass()){
            try{
                object = Integer.valueOf(value);
            }catch (NumberFormatException e){
                value = value.substring(0, value.indexOf("."));
                object = Integer.valueOf(value);
            }
        }
        return object;
    }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值