使用内省的方式操作JavaBean

时间:2023-03-09 20:08:36
使用内省的方式操作JavaBean
  1. import java.beans.BeanInfo;
  2. import java.beans.Introspector;
  3. import java.beans.PropertyDescriptor;
  4. import java.lang.reflect.Field;
  5. import java.lang.reflect.Method;
  6. /**
  7. * 使用内省的方式操作JavaBean
  8. */
  9. public class IntroSpectorTest {
  10. public static void main(String[] args) throws Exception {
  11. ReflectPoint reflectPoint = new ReflectPoint(3,7);
  12. //调用JavaBean中方法的传统作法
  13. Class classz = reflectPoint.getClass();
  14. Field[] fields = classz.getDeclaredFields();
  15. for (Field field : fields) {
  16. String name = "set" + field.getName().toUpperCase();
  17. Method method = classz.getMethod(name, int.class);
  18. method.invoke(reflectPoint, 3);
  19. }
  20. System.out.println(reflectPoint);
  21. //使用内省的方式调用JavaBean的方法
  22. String propertyName = "x";
  23. //获得属性x的值
  24. Object retVal = getProperty2(reflectPoint, propertyName);
  25. System.out.println(retVal);
  26. //设置属性x的值
  27. setProperty(reflectPoint, propertyName,10);
  28. System.out.println(reflectPoint.getX());
  29. }
  30. /**
  31. * 设置属性的值
  32. * @param obj 属性所属的对象
  33. * @param propertyName 属性名
  34. * @param propertyValue 属性值
  35. */
  36. private static void setProperty(Object obj, String propertyName,Object propertyValue) throws Exception {
  37. PropertyDescriptor pd2 = new PropertyDescriptor(propertyName,obj.getClass());
  38. Method setMethod = pd2.getWriteMethod();
  39. setMethod.invoke(obj, propertyValue);
  40. }
  41. /**
  42. * 获得对象的属性值
  43. * @param obj 属性所属的对象
  44. * @param propertyName 属性名
  45. * @return 属性的值
  46. */
  47. private static Object getProperty(Object obj, String propertyName) throws Exception {
  48. PropertyDescriptor pd = new PropertyDescriptor(propertyName,obj.getClass());
  49. Method getMethod = pd.getReadMethod();  //获得get方法
  50. Object retVal = getMethod.invoke(obj);
  51. return retVal;
  52. }
  53. /**
  54. * 使用内省操作javabean
  55. * @param obj 属性所属的对象
  56. * @param propertyName 属性名
  57. * @return 属性的值
  58. */
  59. private static Object getProperty2(Object obj, String propertyName) throws Exception {
  60. Object retVal = null;
  61. BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
  62. PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
  63. for (PropertyDescriptor pd : pds) {
  64. if (pd.getName().equals(propertyName)) {
  65. Method getMethod = pd.getReadMethod();
  66. retVal = getMethod.invoke(obj);
  67. break;
  68. }
  69. }
  70. return retVal;
  71. }
  72. }