java 反射根據屬性替換@值

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;

    }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章