java反射机制实例

1.通过数据库字段反射给对象实例赋值

convertClass.java
/**
   * 通过反射构造对象
   * @param obj
   * @param rs
   * @return
   */
    public Object convertClass(Object obj,ResultSet rs) {
        try {
            //得到元数据
            ResultSetMetaData metaData = rs.getMetaData();
            //遍历元数据
            for(int i=0;i<metaData.getColumnCount();i++) {
                String columName = metaData.getColumnName(i);
                //转换驼峰规则
                String attributeName = StatUtils.lineToHump(columName);
                String attributeValue = rs.getObject(columName) != null ? rs.getObject(columName).toString() : "";
                //特殊字段对格式进行处理
                if(!"".equals(attributeValue)&&"BATCHTIME".equals(columName)) {
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                    attributeValue = format.format(attributeValue);
                }
                StatUtils.setFieldValueByFieldName(obj, attributeName, attributeValue);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return obj;
    }

StatUtils.java
public class StatUtils {

    private static Pattern linePattern = Pattern.compile("_(\\w)");

    public static String chgListStrToInStr(String searchName, List<String> searchIds) {
        if (!StringUtil.isBlank(searchName) && !CollectionUtil.isEmpty(searchIds)) {
            StringBuffer retStr = new StringBuffer();
            for(int i = 0; i < searchIds.size(); ++i) {
                if (i % 1000 == 0) {
                    if (i == 0) {
                        retStr.append(searchName).append(" in (");
                    } else {
                        retStr.append(") or ").append(searchName).append(" in (");
                    }
                } else {
                    retStr.append(" , ");
                }
                retStr.append("'").append((String)searchIds.get(i)).append("'");
            }
            retStr.append(")");
            return retStr.toString();
        } else {
            return "";
        }
    }

    /**
     * 下划线转驼峰
     * @param str
     * @return
     */
    public static String lineToHump(String str){
        str = str.toLowerCase();
        Matcher matcher = linePattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while(matcher.find()){
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * 获取四舍五入
     * @param value
     * @return
     */
    public static String roundHalfUp(double value, int scaleNum) {
        String formatStr = addZeroForNum("0.", (scaleNum+2));
        DecimalFormat df = new DecimalFormat(formatStr);
        double result = new BigDecimal(String.valueOf(value)).setScale(scaleNum, BigDecimal.ROUND_HALF_UP).doubleValue();
        return df.format(result);
    }

    public static String addZeroForNum(String str, int strLength) {
        int strLen = str.length();
        StringBuffer sb = null;
        while (strLen < strLength) {
            sb = new StringBuffer();
            sb.append(str).append("0");//右补0
            str = sb.toString();
            strLen = str.length();
        }
        return str;
    }

    public static Object setFieldValueByFieldName(Object o, String fieldName, Object fieldValue) {
        try {
            Field f = o.getClass().getDeclaredField(fieldName);
            f.setAccessible(true);
            try {
                f.set(o, fieldValue);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        return o;
    }

    /**
     * 根据属性名获取属性值
     *
     * @param fieldName
     * @param object
     * @return
     */
    public static Object getFieldValueByFieldName(String fieldName, Object object) {
        try {
            Field field = object.getClass().getDeclaredField(fieldName);
            //设置对象的访问权限,保证对private的属性的访问
            field.setAccessible(true);
            return field.get(object);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static Map<String, Object> objectToMap(Object obj) throws Exception {
        if(obj == null){
            return null;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        Field[] declaredFields = obj.getClass().getDeclaredFields();
        for (Field field : declaredFields) {
            field.setAccessible(true);
            map.put(field.getName(), field.get(obj));
        }
        return map;
    }

    public static void main(String[] args) {
        System.out.println(roundHalfUp(0.2000606, 6));
    }
}

2.通过对象属性反射给对象赋值

 public static Object initObjects(Object obj,ResultSet rs) {
        
        Field[] fields = obj.getClass().getDeclaredFields();
        for (int i = 0; i <fields.length ; i++) {
            // 取消属性的访问权限控制,即使private属性也可以进行访问。
            fields[i].setAccessible(true);
            String fieldName = fields[i].getName();
            //转大写
            String biColumNameString = fieldName.toUpperCase();
            String columValue;
            try {
                columValue = rs.getObject(biColumNameString) != null ? rs.getObject(biColumNameString).toString() : "";
                fields[i].set(obj, columValue);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }catch (SQLException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
        return obj;
    }
 

猜你喜欢

转载自www.cnblogs.com/pypua/p/10030267.html