黑马程序员技术交流社区

标题: 大家帮我看看是哪里错了 [打印本页]

作者: 丁林    时间: 2011-10-18 22:04
标题: 大家帮我看看是哪里错了
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

public class SetProperty{

        public static void setProperty(Object obj, String propertyName, Object value) throws Exception{
                PropertyDescriptor pd = new PropertyDescriptor(propertyName,Object.class);
                Method methodSetX = pd.getWriteMethod();
                methodSetX.invoke(obj, value);
        }
       
        public static void main(String[] args)throws Exception {
                ReflectPoint rf = new ReflectPoint(3,5);//ReflectPoint类见下边
                setProperty(rf,"x",7);
                System.out.println(rf.getX());
        }
}

public class ReflectPoint {
        private int x;
        public int y;
       
        public ReflectPoint(int x, int y) {//构造方法
                super();
                this.x = x;
                this.y = y;
        }
       
        public int getX() {
                return x;
        }
        public void setX(int x) {
                this.x = x;
        }
}

运行之后提示:
Exception in thread "main" java.beans.IntrospectionException: Method not found: isX
        at java.beans.PropertyDescriptor.<init>(PropertyDescriptor.java:89)
        at java.beans.PropertyDescriptor.<init>(PropertyDescriptor.java:53)
        at practice.five.SetProperty.setProperty(SetProperty.java:10)
        at practice.five.SetProperty.main(SetProperty.java:20)
大家帮我看看是哪里错了?谢谢!
作者: zhangxinxin    时间: 2011-10-18 22:34
public class ReflectPoint {
这个地方错了,两个都声明了public的类,不能存放在一个java文件中。你分别存放
作者: 刘江华    时间: 2011-10-18 23:06
楼上,那异常是说你的方法isX()没有找到,看看 java.beans.PropertyDescriptor这个类里面有没有这个方法。应该不仅仅是一个public 的问题吧。你看那异常信息的意思
作者: 郭敏    时间: 2011-10-18 23:10
将 PropertyDescriptor pd = new PropertyDescriptor(propertyName,Object.class) 方法中 Object.class 改为 ReflectPoint.class, 在试试!
作者: 郭敏    时间: 2011-10-18 23:18
或者将 Object.class 改为 obj.getclass() 在试试!
作者: lvwenwen88    时间: 2012-1-4 22:53
两个都声明了public的类,不能存放在一个java文件中




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