使用BeanUtils设置setter值

sun*_*leo 1 java reflection apache-commons-beanutils

我尝试使用setter设置值但是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;
    }

}
Run Code Online (Sandbox Code Playgroud)

例外:

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
Run Code Online (Sandbox Code Playgroud)

Jay*_*han 12

您的类Test应该是公共类,移动Test到自己的文件,将其公开并重新运行您的代码.


Sha*_*awn 6

将其设置为字段的名称:

BeanUtils.setProperty(t,"te","teval");
Run Code Online (Sandbox Code Playgroud)

文档在这里