3

我尝试使用 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;
    }

}

例外 :

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

您的课程Test应该是公共课程,移动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 

名称是属性名称“te”而不是“setTe”。

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

于 2013-02-14T04:14:58.947 回答
0

该类必须是public,并提供一个不接受任何参数的公共构造函数。这允许工具和应用程序动态创建 bean 的新实例,而不必提前知道将使用什么 Java 类名,如下所示:

     String className = ...;
     Class beanClass = Class.forName(className);
     Object beanInstance = beanClass.newInstance();

http://commons.apache.org/proper/commons-beanutils/javadocs/v1.9.2/apidocs/org/apache/commons/beanutils/package-summary.html#FAQ.property获取

于 2015-12-02T08:45:37.663 回答