黑马程序员技术交流社区

标题: BeanUtils工具出错的一个原因 [打印本页]

作者: 孙胜    时间: 2013-5-3 23:58
标题: BeanUtils工具出错的一个原因
  1. package sheng.java.language;

  2. class Person {
  3.         private String name;
  4.         private int age;

  5.         public String getName() {
  6.                 return name;
  7.         }

  8.         public void setName(String name) {
  9.                 this.name = name;
  10.         }

  11.         public int getAge() {
  12.                 return age;
  13.         }

  14.         public void setAge(int age) {
  15.                 this.age = age;
  16.         }

  17.         public Person(String name, int age) {
  18.                 super();
  19.                 this.name = name;
  20.                 this.age = age;
  21.         }

  22.         public Person() {
  23.                 // TODO Auto-generated constructor stub
  24.         }

  25. }
复制代码
  1. package sheng.java.language;

  2. import java.lang.reflect.InvocationTargetException;

  3. import org.apache.commons.beanutils.BeanUtils;

  4. public class BeanUtilsDemo {

  5.         /**
  6.          * @param args
  7.          * @throws NoSuchMethodException
  8.          * @throws InvocationTargetException
  9.          * @throws IllegalAccessException
  10.          */
  11.         public static void main(String[] args) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
  12.                 // TODO Auto-generated method stub
  13.                 Person p = new Person("zhansan", 23);
  14.                 String name = "age";
  15.                
  16.                 System.out.println(BeanUtils.getProperty(p, name));

  17.         }

  18. }
复制代码
Exception in thread "main" java.lang.NoSuchMethodException: Property 'age' has no getter method in class 'class sheng.java.language.Person'
        at org.apache.commons.beanutils.PropertyUtilsBean.getSimpleProperty(PropertyUtilsBean.java:1327)
        at org.apache.commons.beanutils.PropertyUtilsBean.getNestedProperty(PropertyUtilsBean.java:770)
        at org.apache.commons.beanutils.BeanUtilsBean.getNestedProperty(BeanUtilsBean.java:715)
        at org.apache.commons.beanutils.BeanUtilsBean.getProperty(BeanUtilsBean.java:741)
        at org.apache.commons.beanutils.BeanUtils.getProperty(BeanUtils.java:382)
        at sheng.java.language.BeanUtilsDemo.main(BeanUtilsDemo.java:20)


查明原因后发现Person类必须是public.






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