14

「顧客」の複雑な属性で describe() メソッドを再帰的に呼び出すBeanUtils.describe(customer)のバージョンはありますか。

class Customer {

String id;
Address address;

}

ここでは、describe メソッドで address 属性の内容も取得したいと考えています。

現在、次のようにクラスの名前を確認できます。

{id=123, address=com.test.entities.Address@2a340e}
4

3 に答える 3

11

おかしなことに、describeメソッドでネストされた属性のコンテンツも取得したいのですが、なぜ取得されないのかわかりません。しかし、私は先に進んで自分自身を転がしました。ここにあります、あなたはただ呼び出すことができます:

Map<String,String> beanMap = BeanUtils.recursiveDescribe(customer); 

注意点がいくつかあります。

  1. commons BeanUtilsがコレクション内の属性をどのようにフォーマットしたかわからなかったので、「attribute[index]」を使用しました。
  2. マップ内の属性がどのようにフォーマットされているかわからなかったので、「attribute[key]」を使用しました。
  3. 名前の衝突の場合、優先順位は次のとおりです。最初にプロパティがスーパークラスのフィールドからロードされ、次にクラスからロードされ、次にゲッターメソッドからロードされます。
  4. このメソッドのパフォーマンスは分析していません。コレクションも含むオブジェクトの大規模なコレクションを持つオブジェクトがある場合は、いくつかの問題が発生する可能性があります。
  5. これはアルファコードであり、バグがないことを保証するものではありません。
  6. 私はあなたがコモンズbeanutilsの最新バージョンを持っていると仮定しています

また、fyi、これは私が取り組んできたプロジェクトから大まかに取ったもので、愛情を込めて、刑務所内のjavaと呼ばれているので、ダウンロードして実行するだけです。

Map<String, String[]> beanMap = new SimpleMapper().toMap(customer);

ただし、StringではなくString []が返されることに気付くでしょう。これは、ニーズに合わない場合があります。とにかく、以下のコードは動作するはずですので、それを持ってください!

public class BeanUtils {
    public static Map<String, String> recursiveDescribe(Object object) {
        Set cache = new HashSet();
        return recursiveDescribe(object, null, cache);
    }

    private static Map<String, String> recursiveDescribe(Object object, String prefix, Set cache) {
        if (object == null || cache.contains(object)) return Collections.EMPTY_MAP;
        cache.add(object);
        prefix = (prefix != null) ? prefix + "." : "";

        Map<String, String> beanMap = new TreeMap<String, String>();

        Map<String, Object> properties = getProperties(object);
        for (String property : properties.keySet()) {
            Object value = properties.get(property);
            try {
                if (value == null) {
                    //ignore nulls
                } else if (Collection.class.isAssignableFrom(value.getClass())) {
                    beanMap.putAll(convertAll((Collection) value, prefix + property, cache));
                } else if (value.getClass().isArray()) {
                    beanMap.putAll(convertAll(Arrays.asList((Object[]) value), prefix + property, cache));
                } else if (Map.class.isAssignableFrom(value.getClass())) {
                    beanMap.putAll(convertMap((Map) value, prefix + property, cache));
                } else {
                    beanMap.putAll(convertObject(value, prefix + property, cache));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return beanMap;
    }

    private static Map<String, Object> getProperties(Object object) {
        Map<String, Object> propertyMap = getFields(object);
        //getters take precedence in case of any name collisions
        propertyMap.putAll(getGetterMethods(object));
        return propertyMap;
    }

    private static Map<String, Object> getGetterMethods(Object object) {
        Map<String, Object> result = new HashMap<String, Object>();
        BeanInfo info;
        try {
            info = Introspector.getBeanInfo(object.getClass());
            for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
                Method reader = pd.getReadMethod();
                if (reader != null) {
                    String name = pd.getName();
                    if (!"class".equals(name)) {
                        try {
                            Object value = reader.invoke(object);
                            result.put(name, value);
                        } catch (Exception e) {
                            //you can choose to do something here
                        }
                    }
                }
            }
        } catch (IntrospectionException e) {
            //you can choose to do something here
        } finally {
            return result;
        }

    }

    private static Map<String, Object> getFields(Object object) {
        return getFields(object, object.getClass());
    }

    private static Map<String, Object> getFields(Object object, Class<?> classType) {
        Map<String, Object> result = new HashMap<String, Object>();

        Class superClass = classType.getSuperclass();
        if (superClass != null) result.putAll(getFields(object, superClass));

        //get public fields only
        Field[] fields = classType.getFields();
        for (Field field : fields) {
            try {
                result.put(field.getName(), field.get(object));
            } catch (IllegalAccessException e) {
                //you can choose to do something here
            }
        }
        return result;
    }

    private static Map<String, String> convertAll(Collection<Object> values, String key, Set cache) {
        Map<String, String> valuesMap = new HashMap<String, String>();
        Object[] valArray = values.toArray();
        for (int i = 0; i < valArray.length; i++) {
            Object value = valArray[i];
            if (value != null) valuesMap.putAll(convertObject(value, key + "[" + i + "]", cache));
        }
        return valuesMap;
    }

    private static Map<String, String> convertMap(Map<Object, Object> values, String key, Set cache) {
        Map<String, String> valuesMap = new HashMap<String, String>();
        for (Object thisKey : values.keySet()) {
            Object value = values.get(thisKey);
            if (value != null) valuesMap.putAll(convertObject(value, key + "[" + thisKey + "]", cache));
        }
        return valuesMap;
    }

    private static ConvertUtilsBean converter = BeanUtilsBean.getInstance().getConvertUtils();

    private static Map<String, String> convertObject(Object value, String key, Set cache) {
        //if this type has a registered converted, then get the string and return
        if (converter.lookup(value.getClass()) != null) {
            String stringValue = converter.convert(value);
            Map<String, String> valueMap = new HashMap<String, String>();
            valueMap.put(key, stringValue);
            return valueMap;
        } else {
            //otherwise, treat it as a nested bean that needs to be described itself
            return recursiveDescribe(value, key, cache);
        }
    }
}
于 2011-12-07T19:50:44.077 に答える
6

同じ commom-beanutils から簡単に使用できます。

Map<String, Object> result = PropertyUtils.describe(obj);

指定された Bean が読み取りメソッドを提供するプロパティのセット全体を返します。

于 2014-07-16T00:42:17.553 に答える