黑马程序员技术交流社区

标题: 使用BeanUtils工具类时报错 [打印本页]

作者: 黎志文    时间: 2013-7-19 18:08
标题: 使用BeanUtils工具类时报错
本帖最后由 黎志文 于 2013-7-20 15:35 编辑

  1. package cn.itcast.day3;
  2. import org.apache.commons.beanutils.BeanUtils;
  3. class Student  
  4. {
  5.     private int age;

  6.     Student(int age)
  7.     {
  8.         this.age = age;
  9.     }
  10.     public int getAge() {
  11.         return age;
  12.     }
  13.     public void setAge(int age) {
  14.         this.age = age;
  15.     }
  16. }
  17. //使用BeanUtils工具类对上述Student类中的age属性值进行设置
  18. class BeanUtilsDemo {

  19.     public static void main(String[] args) throws Exception {

  20.         Student stu = new Student(22);
  21.         BeanUtils.setProperty(stu,"age",30);
  22.     }
  23. }
复制代码
程序运行后,总是提示:Exception in thread "main" java.lang.reflect.InvocationTargetException: Cannot set age
Caused by: java.lang.NoSuchMethodException: Property 'age' has no setter method in class 'class cn.itcast.day3.Student'
Student类中不是已经有了getter和setter方法么,为何这里总提示说没有setter方法?


作者: majunm    时间: 2013-7-19 18:34
public Student(int age)
{
       this.age=age;
}//试试
作者: 付龙    时间: 2013-7-19 19:53
没有获取JavaBean的Method方法怎么会设置成功呢  可以试一下
  1. PropertyDescriptor pd2 = new PropertyDescriptor("age",stu.getClass());
  2.                 Method ageSet = pd2.getWriteMethod();
  3.                 ageSet.invoke(stu,26);
  4.                 System.out.println(stu.getAge());
复制代码

作者: 黎志文    时间: 2013-7-20 15:34
majunm 发表于 2013-7-19 18:34
public Student(int age)
{
       this.age=age;

试过,确实是因为Student前面没有加上public所引起的,谢谢!
作者: majunm    时间: 2013-7-20 15:38
黎志文 发表于 2013-7-20 15:34
试过,确实是因为Student前面没有加上public所引起的,谢谢!

我记得好像是这样子的  是你让我记忆更加深刻 我也谢谢你..
作者: 风爽    时间: 2013-7-27 15:31
我加上public还是有同样的错误
作者: 风爽    时间: 2013-7-27 15:35
能给解决下不

作者: toShareBeauty    时间: 2013-7-27 15:42
必须是 public 的类




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2