java反射机制实例

Posted 十月围城小童鞋

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
    }

 

 

 



以上是关于java反射机制实例的主要内容,如果未能解决你的问题,请参考以下文章

java反射机制的作用与优点

Java基础Java反射机制浅解

反射机制入门

反射机制入门

反射机制入门

Java反射机制详解