3

セッターを使用して値を設定しようとしましたが、null が来ました。

import org.apache.commons.beanutils.BeanUtils;

public class TestSetter {

    public static void main(String args[]) throws Exception
    {
        Test t = new Test();
        BeanUtils.setProperty(t,"te","teval");
        System.out.println("tevalue :"+t.getTe());
    }
}
class Test
{
    String te;

    public String getTe() {
        return te;
    }

    public void setTe(String te) {
        this.te = te;
    }

}

例外 :

Exception in thread "main" java.lang.reflect.InvocationTargetException: Cannot set te
    at org.apache.commons.beanutils.BeanUtilsBean.setProperty(BeanUtilsBean.java:1025)
    at org.apache.commons.beanutils.BeanUtils.setProperty(BeanUtils.java:313)
    at test.reflection.TestSetter.main(TestSetter.java:10)
Caused by: java.lang.NoSuchMethodException: Property 'te' has no setter method
    at org.apache.commons.beanutils.PropertyUtilsBean.setSimpleProperty(PropertyUtilsBean.java:1746)
    at org.apache.commons.beanutils.PropertyUtilsBean.setNestedProperty(PropertyUtilsBean.java:1648)
    at org.apache.commons.beanutils.PropertyUtilsBean.setProperty(PropertyUtilsBean.java:1677)
    at org.apache.commons.beanutils.BeanUtilsBean.setProperty(BeanUtilsBean.java:1022)
    ... 2 more
4

4 に答える 4

13

あなたのクラスはpublicTest class である必要があります。独自のファイルに移動し、公開してコードを再実行してください。Test

于 2013-02-14T04:17:27.263 に答える
6

フィールドの名前に設定します。

BeanUtils.setProperty(t,"te","teval");

ドキュメントはこちら

于 2013-02-14T04:10:36.030 に答える
0

のメソッドシグネチャsetProperty()

public static void setProperty(Object bean,
                               String name,
                               Object value)
                        throws IllegalAccessException,
                               InvocationTargetException

    Parameters:
        bean - Bean on which setting is to be performed
        name - Property name (can be nested/indexed/mapped/combo)
        value - Value to be set 

name は "setTe" ではなくプロパティ名 "te" です。

BeanUtils.setProperty(t,"te","teval");

于 2013-02-14T04:14:58.947 に答える