springboot反射实体类赋值

 /**
     * 反射实体赋值
     *@param spEquipment 实体对象
     * @param name 反射字段
     * @param o 反射赋值
     * @return
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     */
    private SpEquipment getSpEquipment(SpEquipment spEquipment,String name, String o) {
        // 获取实体类的所有属性,返回Field数组
        Field field = null;
        try {
        //替换下划线
        if(name.indexOf("_")!=-1){
            String[] s = name.split("_");
            name=s[0];
            for (int i = 1; i < s.length; i++) {
                String first = s[i].substring(0, 1);
                String after = s[i].substring(1);
                first = first.toUpperCase();
                after = after.toLowerCase();
                s[i]=first+after;
                name+=s[i];
            }
        }
        System.out.println(name);
        field = spEquipment.getClass().getDeclaredField(name);
        field.setAccessible(true);
        Type type = field.getGenericType();
            if ("class java.lang.String".equals(type.toString())) {
                field.set(spEquipment,o);
            } else if ("class java.lang.Integer".equals(type.toString())) {
                if(!"".equals(o)&&null!=o) {
                    field.set(spEquipment, Integer.parseInt(o));
                }
            } else if ("class java.lang.Boolean".equals(type.toString())) {
                if(o.equals("on")){
                    o="1";
                }
                if(o.equals("off")){
                    o="0";
                }
                field.set(spEquipment,"1".equals(o)?true:false);
            }else if ("class java.lang.Double".equals(type.toString())) {
                field.set(spEquipment,Double.parseDouble(o));
            }else if ("class java.lang.Float".equals(type.toString())) {
                field.set(spEquipment,Float.parseFloat(o));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return spEquipment;
    }

你可能感兴趣的:(java,spring,boot)