-1

ファイルから文字列形式で取得した値があります。

たとえば、ファイル AI には次のものがあります。

id = 342
name = Jonatan
country = USA

さらにperson、次のフィールドを持つ class: があります。

String id;
String name;
String country;
String grades;
String location;

すべてのフィールドにゲッターとセッターがあります。

ここで、Jonatan を表す person の新しいインスタンスを作成したいと思います。しかし、すべてのフィールドを更新するのではなく、必要なフィールドだけを更新したいのです。

だから、私がやりたいことは次のことです: ファイルから詳細を取得し、すべての設定を行い、正しい値を更新します。たとえば、setName(Jonatan). 問題は、 mynameが文字列形式であることです。名前は文字列形式であり、Java は文字列形式でメソッドを呼び出すオプションを提供しないため、setName を実行できません。

簡単な方法はありますか?

4

3 に答える 3

3

Apache BeanUtilsを見ているかもしれません

アプリケーションは非常に単純です - 個人呼び出しの setId("42") を呼び出します:

PropertyUtils.setSimpleProperty(person, "id", "42");
于 2013-03-17T15:23:34.280 に答える
1

Java リフレクションを使用すると、使用可能なメソッド/フィールドを特定できます。

この例を使用して、キーと値のペアをdoReflectionメソッドに渡し、Bean クラスのインスタンスにプロパティの新しい値を設定できます。

public class Bean {

    private String id = "abc";

    public void setId(String s) {
        id = s;
    }

    /**
     * Find a method with the given field-name (prepend it with "set") and
     * invoke it with the given new value.
     * 
     * @param b The object to set the new value onto
     * @param field  The name of the field (excluding "set")
     * @param newValue The new value
     */
    public static void doReflection(Bean b, String field, String newValue) throws NoSuchMethodException,
            SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        Class<? extends Bean> c = b.getClass();
        Method id = c.getMethod("set" + field, String.class);
        id.invoke(b, newValue);
    }

    public static void main(String... args) throws NoSuchMethodException, SecurityException, IllegalArgumentException,
            InvocationTargetException, IllegalAccessException {
        Bean bean = new Bean();
        System.out.println("ID before: " + bean.id);
        doReflection(bean, "Id", "newValue");
        System.out.println("ID after: " + bean.id);

        // If you have a map of key/value pairs:
        Map<String, String> values = new HashMap<String, String>();
        for(Entry<String, String> entry : values.entrySet())
            doReflection(bean, entry.getKey(), entry.getValue());
    }
于 2013-03-17T15:20:30.610 に答える
1

@michael_s の答えが好きBeanUtilsです。なしでやりたい場合は、次のように書くことができます。

Person person = new Person();
Properties properties = new Properties();
properties.load(new FileInputStream("the.properties"));
for (Object key : properties.keySet()) {
    String field = (String) key;
    String setter = "set" + field.substring(0, 1).toUpperCase() + field.substring(1);
    Method method = Person.class.getMethod(setter, String.class);
    method.invoke(person, properties.get(key));
}

使用後にストリームを閉じる必要があるわけではなく、この短い例はStringプロパティに対してのみ機能します。

于 2013-03-17T15:35:04.487 に答える