黑马程序员技术交流社区

标题: BeanUtils中设置出生日期为啥老是出错??? [打印本页]

作者: 黑马_位志国    时间: 2013-4-3 10:57
标题: BeanUtils中设置出生日期为啥老是出错???
本帖最后由 黑马_位志国 于 2013-4-10 07:27 编辑

JavaBean文件:
import java.util.*;

public class Person {
        private String name;
        private int age;
        private Date birthday;
        public Person(String name, int age) {
                this.name = name;
                this.age = age;
        }
        public String getName() {
                return name;
        }
        public void setName(String name) {
                this.name = name;
        }
        public int getAge() {
                return age;
        }
        public void setAge(int age) {
                this.age = age;
        }
        public Date getBirthday() {
                return birthday;
        }
        public void setBirthday(Date birthday) {
                this.birthday = birthday;
        }
        
}

实例:
import java.beans.*;
import java.lang.reflect.*;

import org.apache.commons.beanutils.BeanUtils;

public class PersonTest {

        /**
         * @param args
         * @throws IntrospectionException
         * @throws InvocationTargetException
         * @throws IllegalArgumentException
         * @throws IllegalAccessException
         * @throws NoSuchMethodException
         */
        public static void main(String[] args) throws IntrospectionException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException {
                // TODO Auto-generated method stub

                Person p = new Person("ijunfu", 23);
                BeanUtils.setProperty(p, "birthday.time", "111");
                System.out.println(BeanUtils.getProperty(p, "birthday.time"));
        }
}

为什么老是出现以下错误???
Exception in thread "main" java.lang.IllegalArgumentException: No bean specified
        at org.apache.commons.beanutils.PropertyUtilsBean.getPropertyDescriptor(PropertyUtilsBean.java:883)
        at org.apache.commons.beanutils.BeanUtilsBean.setProperty(BeanUtilsBean.java:935)
        at org.apache.commons.beanutils.BeanUtils.setProperty(BeanUtils.java:456)
        at com.ijunfu.study.java.enhance.day01.PersonTest.main(PersonTest.java:35)

求教......

作者: 932759732    时间: 2013-4-7 16:08
本帖最后由 杨玄文 于 2013-4-7 16:19 编辑

public class Person {
        private String name;
        private int age;
        private Date birthday = new Date();
        public Person(String name, int age) {
                this.name = name;
                this.age = age;
        }

把前面改成这样就好了。
private Date birthday = new Date();

因为你的brithday中本身是没有.time属性的
只有成为Date()的实例对象才会有time这个属性。

所以你在后面传入 birthday.time会报错。

我之前也遇到过这个问题,想了好久没想明白,最后看了下文档,才恍然大悟




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