我尝试使用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
答案 0 :(得分:12)
您的课程Test
应为公开课程,将Test
移至自己的文件,公开并重新运行您的代码。
答案 1 :(得分:6)
答案 2 :(得分: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是属性名称“te”而不是“setTe”。
BeanUtils.setProperty(T, “TE”, “teval”);
答案 3 :(得分:0)
该类必须是 public ,并提供一个公共构造函数 不接受任何参数。这允许工具和应用程序 动态创建bean的新实例,但不一定 知道将提前使用什么Java类名称,如下所示:
String className = ...;
Class beanClass = Class.forName(className);
Object beanInstance = beanClass.newInstance();