7

私はビーンを持っています。ビーンのすべてのプロパティを1つずつリストせずにリストする方法はありますか?

一部の Bean は、便利な ToString() メソッドをオーバーライドします。このメソッドをオーバーライドしない Bean はどうですか?

4

4 に答える 4

10

次のように、BeanIntrospection を介してBeanInfoを使用できます。

Object o = new MyBean();
try {
    BeanInfo bi = Introspector.getBeanInfo(MyBean.class);
    PropertyDescriptor[] pds = bi.getPropertyDescriptors();
    for (int i=0; i<pds.length; i++) {
        // Get property name
        String propName = pds[i].getName();

        // Get the value of prop1
        Expression expr = new Expression(o, "getProp1", new Object[0]);
        expr.execute();
        String s = (String)expr.getValue();
    }
    // class, prop1, prop2, PROP3
} catch (java.beans.IntrospectionException e) {
}

または、次のアプローチのいずれかを使用してリフレクション メソッドを使用することもできます。

  1. getDeclaredMethods を介してパラメーターのない getXXX() メソッドをすべて取得し、それらをトラバースします。
  2. getDeclaredFields() を使用してすべてのフィールドを取得し、それらをトラバースします (気になる場合は、Bean 仕様に準拠していません)
于 2012-05-26T09:16:32.037 に答える
4

apachecommonslangを参照してください-ReflectionToStringBuilder

于 2012-05-26T09:25:00.657 に答える
2

リフレクションを使用できます。クラスから宣言されたフィールドを取得します。セッターとゲッターがあるかどうかはプライベートチェックです(ブールゲッターは「isProperty」であることを忘れないでください)。

コードは次のようになります。

List<String> properties = new ArrayList<String>();
Class<?> cl = MyBean.class;

// check all declared fields
for (Field field : cl.getDeclaredFields()) {

    // if field is private then look for setters/getters
    if (Modifier.isPrivate(field.getModifiers())) {

        // changing 1st letter to upper case
        String name = field.getName();
        String upperCaseName = name.substring(0, 1).toUpperCase()
                + name.substring(1);
        // and have getter and setter
        try {
            String simpleType = field.getType().getSimpleName();
            //for boolean property methods should be isProperty and setProperty(propertyType)
            if (simpleType.equals("Boolean") || simpleType.equals("boolean")) {
                if ((cl.getDeclaredMethod("is" + upperCaseName) != null)
                        && (cl.getDeclaredMethod("set" + upperCaseName,
                                field.getType()) != null)) {
                    properties.add(name);
                }
            } 
            //for not boolean property methods should be getProperty and setProperty(propertyType)
            else {
                if ((cl.getDeclaredMethod("get" + upperCaseName) != null)
                        && (cl.getDeclaredMethod("set" + upperCaseName,
                                field.getType()) != null)) {
                    properties.add(name);
                }
            }
        } catch (NoSuchMethodException | SecurityException e) {
            // if there is no method nothing bad will happen
        }
    }
}
for (String property:properties)
    System.out.println(property);
于 2012-05-26T09:57:57.940 に答える
0

BeanInfoに興味があるかもしれません。これは、Beanクラスを変更する必要がなくても、Beanクラスに付随する可能性のあるクラスです。多くのGUIビルダーでBeanのプロパティを表示するために使用されますが、GUI以外の用途もあります。

于 2012-05-26T09:42:50.903 に答える