java 反射根据属性替换@值

来源:互联网 发布:matlab矩阵归一化程序 编辑:程序博客网 时间:2024/05/22 20:27
private static final String PREFIX = "@"; // 规则侦测中值得前缀    /**     *     * @Title: replaceStr     * @Description: TODO(根据@Column 替换交易信息中的值)     * @param obj 交易信息Bean    * @param sql sql语句    * @return    * @throws Exception    * @throws     */    public static String replaceStr(Object obj, String sql)            throws Exception {        if (obj == null) {            return null;        }        Map<String, Object> map = new HashMap<String, Object>();        try {            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass()); // 获取Bean信息            PropertyDescriptor[] propertyDescriptors = beanInfo                    .getPropertyDescriptors(); // 获取属性            Map<String, String> annoMap = new HashMap<String, String>();            Field[] fields = obj.getClass().getDeclaredFields(); // 获取类的字段            for (Field field : fields) { // 获取类中字段上有注解的                if (field.isAnnotationPresent(Column.class)) {                    Column mfk = field.getAnnotation(Column.class);                    annoMap.put(field.getName(), mfk.name());// 获取有注解的原始字段和对应的映射字段                }            }            for (PropertyDescriptor property : propertyDescriptors) {                String key = property.getName();                // 过滤class属性                if (!key.equals("class")) {                    // 得到property对应的getter方法                    Method getter = property.getReadMethod();                    Object value = getter.invoke(obj);                    if (null != annoMap.get(key)) {                        if (property.getPropertyType().toString()                                .equals("class java.lang.String")) { // 首先判断String                            if (null != value) {                                // 如果是varchar需要在结果的前后加''号                                map.put(PREFIX + annoMap.get(key),                                        "'" + value + "'");                            }                        } else if (property.getPropertyType().toString()                                .equals("class java.lang.Integer")) { // Integer类型                            if (null != value) {                                // 如果是int类型的直接加值                            Integer val = Integer.parseInt(value.toString());                                map.put(PREFIX + annoMap.get(key), val);                            }                        }                    }                }            }        } catch (Exception e) {            throw new Exception("替换@对应的值异常", e);        }        for (String key : map.keySet()) { // 将所有的不为null的值替换到sql语句中            sql = sql.replace(key, map.get(key).toString());        }        return sql;    }


0 0
原创粉丝点击