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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 凡延海 中级黑马   /  2012-5-30 15:08  /  1333 人查看  /  5 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

对JavaBean内省的操作张老师演示了用PropertyDescriptor编写一个方法setProperty()来给一个实例对象的属性赋值。我用BeanInfo类来编写,编译的时候没有错误,就是运行的时候不能通过,我就是找不出愿意来,求助大家了。
  1. import java.beans.*;
  2. import java.lang.reflect.Method;
  3. import java.beans.Introspector;
  4. public class SetProperty {
  5. private String name;
  6. private int age;
  7. public String getName()
  8. {
  9. return name;
  10. }
  11. public int getAge()
  12. {
  13. return age;
  14. }
  15. public void setName(String name)
  16. {
  17. this.name=name;
  18. }
  19. public void setAge(int age)
  20. {
  21. this.age=age;
  22. }
  23. public SetProperty(String name,int age)
  24. {
  25. this.name=name;
  26. this.age=age;
  27. }
  28. public void setProperty(Object obj, String propertyName, Object value) throws Exception
  29. {
  30. BeanInfo beanInfo=Introspector.getBeanInfo(obj.getClass());
  31. PropertyDescriptor[] pds=beanInfo.getPropertyDescriptors();
  32. for(PropertyDescriptor pd:pds)
  33. {
  34. if(pd.getName().equals(propertyName));
  35. {
  36. Method methodSet=pd.getWriteMethod();
  37. methodSet.invoke(obj, value);
  38. }
  39. }
  40. }
  41. public static void main(String[] args) {
  42. try
  43. {
  44. SetProperty setP=new SetProperty("Tom",20);
  45. setP.setProperty(setP,"name","Tom");
  46. setP.setProperty(setP,"age",30);
  47. System.out.println("name:"+setP.getName());
  48. System.out.println("age:"+setP.getAge());
  49. }
  50. catch(Exception e)
  51. {
  52. e.printStackTrace();
  53. }
  54. }
  55. }
复制代码

5 个回复

倒序浏览
老大,你34行后面多了个分号,去了就OK了
回复 使用道具 举报
{:soso_e113:}   呵呵
回复 使用道具 举报
呵呵,34行多了分号,分号就是一条语句。你后边的大括号意义就变化了{:soso_e100:}
回复 使用道具 举报
呵呵,34行多了分号,分号就是一条语句。你后边的大括号意义就变化了{:soso_e100:}
回复 使用道具 举报
小问题造成大麻烦,我愣是没有看出来,唉。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马