A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 郭敏 黑马帝   /  2011-10-26 11:25  /  2065 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. import java.beans.PropertyDescriptor;

  2. import java.lang.reflect.Method;

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

  4. public class IntroSpectorTest {

  5.      
  6.         public static void main(String[] args) throws Exception {
  7.            ReflectPoint pt=new ReflectPoint(3,5);
  8.            
  9.            String propertyName="x";
  10.            PropertyDescriptor pd = new PropertyDescriptor(propertyName, pt.getClass());
  11.            Method methodGetX1 = pd.getReadMethod();
  12.            System.out.println(methodGetX1.invoke(pt));
  13.            
  14.            System.out.println(BeanUtils.getProperty(pt, propertyName));
  15.            
  16.    
  17.           System.out.println( pt.getX());
  18.         }      
  19. }

  20. class ReflectPoint {
  21.         private int x;
  22.         private int y;
  23.        
  24.         public ReflectPoint(int x,int y) {
  25.        
  26.                 this.x = x;
  27.                 this.y = y;
  28.         }
  29.         public int getX() {
  30.                 return x;
  31.         }
  32.         public void setX(int x) {
  33.                 this.x = x;
  34.         }
  35.         public int getY() {
  36.                 return y;
  37.         }
  38.         public void setY(int y) {
  39.                 this.y = y;
  40.         }
  41. }
复制代码
运行里,提示
Exception in thread "main" java.lang.NoSuchMethodException: Property 'x' has no getter method in class 'class ReflectPoint'
        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 IntroSpectorTest.main(IntroSpectorTest.java:18)

1 个回复

倒序浏览
声明bean为public class xxx,必须是public,我用默认类型(class xxx)都不行
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马