[关闭]
@liayun 2016-06-24T09:45:26.000000Z 字数 11917 阅读 1824

内省

java基础加强


了解JavaBean

内省综合案例

内省访问JavaBean属性的两种方式:

案例一:
有类ReflectPoint如下:

  1. public class ReflectPoint {
  2. private int x;
  3. public int y;
  4. public String str1 = "ball";
  5. public String str2 = "basketball";
  6. public String str3 = "itcast";
  7. public ReflectPoint(int x, int y) { // 快捷键——Alt+Shift+S + O
  8. super();
  9. this.x = x;
  10. this.y = y;
  11. }
  12. @Override
  13. public String toString() {
  14. return str1 + ":" + str2 + ":" + str3;
  15. }
  16. @Override
  17. public int hashCode() {
  18. final int prime = 31;
  19. int result = 1;
  20. result = prime * result + x;
  21. result = prime * result + y;
  22. return result;
  23. }
  24. @Override
  25. public boolean equals(Object obj) {
  26. if (this == obj)
  27. return true;
  28. if (obj == null)
  29. return false;
  30. if (getClass() != obj.getClass())
  31. return false;
  32. ReflectPoint other = (ReflectPoint) obj;
  33. if (x != other.x)
  34. return false;
  35. if (y != other.y)
  36. return false;
  37. return true;
  38. }
  39. public int getX() {
  40. return x;
  41. }
  42. public void setX(int x) {
  43. this.x = x;
  44. }
  45. public int getY() {
  46. return y;
  47. }
  48. public void setY(int y) {
  49. this.y = y;
  50. }
  51. }

案例二:
有类Person如下:

  1. public class Person { // javabean
  2. private String name; // 字段
  3. private String password; // 字段
  4. private int age; // 字段
  5. // 注意:Person类从Object类继承了getClass()方法,所以还有一个class属性
  6. public String getAb() {
  7. return null;
  8. }
  9. public String getName() {
  10. return name;
  11. }
  12. public void setName(String name) {
  13. this.name = name;
  14. }
  15. public String getPassword() {
  16. return password;
  17. }
  18. public void setPassword(String password) {
  19. this.password = password;
  20. }
  21. public int getAge() {
  22. return age;
  23. }
  24. public void setAge(int age) {
  25. this.age = age;
  26. }
  27. }

注意:Person类从Object类继承了getClass()方法,所以还有一个class属性
使用内省api操作bean的属性。

使用beanUtils操纵javabean

Sun公司的内省API过于繁琐,所以Apache组织结合很多实际开发中的应用场景开发了一套简单、易用的API操作Bean的属性——BeanUtils,在BeanUtils中可以直接进行类型的自动转换。
Beanutils工具包的常用类:
①BeanUtils
②PropertyUtils
③ConvertUtils.regsiter(Converter convert, Class clazz)`
④自定义转换器

记录遇到的一个error

The project was not built due to "Could not write file: E:\MyJava\java_adv\javaenhance\bin\cn.". Fix the problem, then try refreshing this project and building it since it may be inconsistent.

借助有道翻译为:

此项目由于不能写入文件E:\MyJava\java_adv\javaenhance\bin\cn而不能被构建。解决此问题,试着刷新该项目并构建,因为它可能是不一致的。

我也不知道是什么情况,只能百度了,查到解决办法如下:
工程有错误的话,用下eclipse的projectclean

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注