9

Can we find setter method name using property name?

I have a dynamically generated map<propertyName,propertyValue>

By using the key from map (which is propertyName) I need to invoke the appropriate setter method for object and pass the value from map (which is propertyValue).

class A {
    String name;
    String age;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getCompany() {
        return company;
    }
    public void setCompany(String company) {
        this.company = company;
    }
}

My map contain two items:

map<"name","jack">
map<"company","inteld">

Now I am iterating the map and as I proceed with each item from map, based on key (either name or company) I need to call appropriate setter method of class A e.g. for first item I get name as key so need to call new A().setName.

4

7 に答える 7

20

これはリフレクションを使用して実行できますが、commons-beanutilsを使用した方がよい場合があります。setSimpleProperty()次のように簡単にメソッドを使用できます。

PropertyUtils.setSimpleProperty(a, entry.getKey(), entry.getValue());

aがタイプであると仮定しAます。

于 2013-02-27T14:58:56.727 に答える
13

Springを使用する場合は、を使用することをお勧めしますBeanWrapper。(そうでない場合は、使用を検討してください。)

Map map = new HashMap();
map.put("name","jack");
map.put("company","inteld");

BeanWrapper wrapper = new BeanWrapperImpl(A.class);
wrapper.setPropertyValues(map);
A instance = wrapper.getWrappedInstance();

Springは一般的な型変換を行うため、これはリフレクションを直接使用するよりも簡単です。(Javaプロパティエディタも尊重するため、処理しないものにカスタムタイプコンバータを登録できます。)

于 2013-02-27T15:18:09.477 に答える
5

Reflection API必要なものです。aプロパティ名を知っていて、 typeのオブジェクトがあると仮定しましょうA:

 String propertyName = "name";
 String methodName = "set" + StringUtils.capitalize(propertyName);
 a.getClass().getMethod(methodName, newObject.getClass()).invoke(a, newObject);

もちろん、いくつかの例外を処理するよう求められます。

于 2013-02-27T15:03:07.377 に答える
2

次のようなセッターメソッドを取得できます。

A a = new A();
String name = entry.getKey();
Field field = A.class.getField(name);
String methodName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1);
Method setter = bw.getBeanClass().getMethod(methodName, (Class<?>) field.getType());
setter.invoke(a, entry.getValue());

しかし、それはあなたのAクラスでしか機能しません。基本クラスを拡張したクラスがある場合、class.getField(name) はまだ機能していません。

Juffrou-reflectの BeanWrapper を見てください。Springframework よりもパフォーマンスが高く、map-bean 変換などを行うことができます。

免責事項: 私は Juffrou-reflect を開発した者です。また、使い方についてご不明な点がございましたら、お気軽にお問い合わせください。

于 2013-06-15T17:31:16.693 に答える
-1

おそらくリフレクションでそれを行うことができると思います。より簡単な解決策は、キーで文字列比較を行い、適切なメソッドを呼び出すことです:

 String key = entry.getKey();
 if ("name".equalsIgnoreCase(key))
   //key
 else
   // company
于 2013-02-27T14:55:33.370 に答える