BeanUtils 工具类

一.BeanUtils 概述
     BeanUtils 是阿帕奇提供的一套专门用于将一些数据封装到java对象中的工具类;
    
     名词:javaBean:特定格式的java类称为javaBean;
    
     要求:
         1:javaBean这个类要实现Serializable接口;(在实际开发中,通常省略了)
         2:javaBean必须有public权限的空参数的构造方法;
         3:javaBean必须有属性对应的getXxx与setter方法;

二.BeanUtils 的使用
     Beanutils 有2个依赖jar包;commons-beanutils-1.8.3.jar和commons-logging-1.1.1.jar;
     BeanUtils 有2个核心类:BeanUtils,ConvertUtils 类;
     使用步骤:
         1:下载解压;
         2:复制核心jar包到工程中;(有2个)
         3:添加到本地;(add to build path)
         4:使用核心类;

三.BeanUtils 常用方法
     public static void setProperty(Object bean,String name,Object value)
                             throws IllegalAccessException,InvocationTargetException{}:向bean对象的name属性中保存value值;
     public static String getProperty(Object bean,String name)
                               throws IllegalAccessException,InvocationTargetException,NoSuchMethodException{}:从bean对象中获取name属性的值;
     public static String[] getArrayProperty(Object bean,String name)
                                      throws IllegalAccessException,InvocationTargetException,NoSuchMethodException{}:从bean对象中获取name属性的数组类型的值;
     [注:getProperty方法就只认String类型和String[]数组类型,其它类型它会自动帮你转成这两个类型,使用时需时刻想到String类型,用""包裹属性]
     public static void populate(Object bean,Map properties)
                                     throws IllegalAccessException,InvocationTargetException{}:将properties集合中的数据,根据key与bean的属性名(实际上是匹配setXxx方法)    匹配,匹配成功,则赋值,匹配失败不操作;                                                   
代码演示1:(以下代码全在Eclipse中实现)

  1 //创建beanUtilsDemo01包
  2 package beanUtilsDemo01;
  3 
  4 import java.util.Arrays;
  5 
  6 public class Person {
  7      // 属性
  8     private String name;
  9      private int age;
 10      private String[] hobby;
 11 
 12     // 构造方法
 13     public Person() {
 14         super();
 15      }
 16 
 17     public Person(String name, int age, String[] hobby) {
 18          super();
 19          this.name = name;
 20          this.age = age;
 21          this.hobby = hobby;
 22      }
 23 
 24     // getter/setter
 25      public String getName() {
 26          return name;
 27      }
 28 
 29     public void setName(String name) {
 30          this.name = name;
 31      }
 32 
 33     public int getAge() {
 34          return age;
 35      }
 36 
 37     public void setAge(int age) {
 38          this.age = age;
 39      }
 40 
 41     public String[] getHobby() {
 42          return hobby;
 43      }
 44 
 45     public void setHobby(String[] hobby) {
 46          this.hobby = hobby;
 47      }
 48 
 49     // 覆写toString/equal/hashcode
 50      @Override
 51      public String toString() {
 52          return "Person [name=" + name + ", age=" + age + ", hobby="
 53                  + Arrays.toString(hobby) + "]";
 54      }
 55 
 56     @Override
 57      public int hashCode() {
 58          final int prime = 31;
 59          int result = 1;
 60          result = prime * result + age;
 61          result = prime * result + Arrays.hashCode(hobby);
 62          result = prime * result + ((name == null) ? 0 : name.hashCode());
 63          return result;
 64      }
 65 
 66     @Override
 67      public boolean equals(Object obj) {
 68          if (this == obj) {
 69              return true;
 70          }
 71          if (obj == null) {
 72              return false;
 73          }
 74          if (!(obj instanceof Person)) {
 75              return false;
 76          }
 77          Person other = (Person) obj;
 78          if (age != other.age) {
 79              return false;
 80          }
 81          if (!Arrays.equals(hobby, other.hobby)) {
 82              return false;
 83          }
 84          if (name == null) {
 85              if (other.name != null) {
 86                  return false;
 87              }
 88          } else if (!name.equals(other.name)) {
 89              return false;
 90          }
 91          return true;
 92      }
 93 
 94 }
 95  //创建beanUtilsDemo01包
 96 package beanUtilsDemo01;
 97 
 98 import java.util.Arrays;
 99 
100 import org.apache.commons.beanutils.BeanUtils;
101 
102 //BeanUtils常用方法练习
103 
104 public class Demo01BeanUtils {
105 
106     public static void main(String[] args) throws Exception {
107          // 实例化对象
108         Person p = new Person();
109          // 借用BeanUtils工具类向Person对象赋值
110         BeanUtils.setProperty(p, "name", "Rose");
111          BeanUtils.setProperty(p, "age", 22);
112          BeanUtils.setProperty(p, "hobby", new String[] { "eating", "sleeping",
113                  "kissing" });
114          // 打印对象
115         System.out.println(p);
116          // 获取各属性值
117         String[] hobby = BeanUtils.getArrayProperty(p, "hobby");
118          System.out.println(Arrays.toString(hobby));
119          String name = BeanUtils.getProperty(p, "name");
120          System.out.println(name);
121          String age = BeanUtils.getProperty(p, "age");
122          System.out.println(age);
123      }
124 
125 }
126 


代码演示2:封装map集合中的数据

  1 package beanUtilsDemo01;
  2 
  3 import java.lang.reflect.InvocationTargetException;
  4  import java.util.HashMap;
  5  import java.util.Map;
  6 
  7 import org.apache.commons.beanutils.BeanUtils;
  8 
  9 //借用BeanUtils将Map中的数据封装到javabean中
 10 
 11 public class Demo02BeanUtils {
 12 
 13     public static void main(String[] args) throws IllegalAccessException,
 14              InvocationTargetException {
 15          // 实例化对象
 16         Person p = new Person();
 17          // 准备MAP集合
 18         Map<String, Object> map = new HashMap<>();
 19          // 向map中添加数据
 20         map.put("name", "jack");
 21          map.put("age", 23);
 22          map.put("hobbyy", new String[] { "eating", "sleeping", "painting" });
 23          // 将map集合中的数据封装到javabean中
 24         BeanUtils.populate(p, map);
 25          System.out.println(p);
 26      }
 27  }
 28 


代码演示3:与以上利用同一个Person类????????????????????????

  1 package beanUtilsDemo01;
  2 
  3 import java.util.HashMap;
  4  import java.util.Map;
  5 
  6 import org.apache.commons.beanutils.BeanUtils;
  7 
  8 //利用BeanUtils工具类自定义工具类:要求传入任一类型的字节码文件 和 属性的map集合,返回实例化对象
  9 class MyBeanUtils {
 10      public static <T> T popu(Class<T> c, Map map) throws Exception {    //泛型
 11         Object obj = c.newInstance();
 12          BeanUtils.populate(obj, map);
 13          return (T) obj; //向下转型
 14     }
 15  }
 16 
 17 public class MyTest {
 18      public static void main(String[] args) throws Exception {
 19         Map<String, Object> map = new HashMap<>();
 20          map.put("name", "rose");
 21          map.put("age", "18");
 22          Person p = MyBeanUtils.popu(Person.class, map);
 23          System.out.println(p);
 24      }
 25 
 26 }
 27 


代码演示4:需准备一个User类,和以上的Person类,及data.xml文件

  1 package beanutilcase;
  2 
  3 import java.util.HashMap;
  4  import java.util.List;
  5  import java.util.Map;
  6 
  7 import org.apache.commons.beanutils.BeanUtils;
  8  import org.dom4j.Document;
  9  import org.dom4j.Element;
 10  import org.dom4j.io.SAXReader;
 11 
 12 public class Demo {
 13 
 14     public static void main(String[] args) throws Exception {
 15          Person p = new Person();
 16          User u = new User();
 17          // 创建解析器对象
 18         SAXReader sax = new SAXReader();
 19          // 读取文档,并获取根节点
 20         Document doc = sax.read("data.xml");
 21          Element root = doc.getRootElement();
 22          // 获取根节点下的一级子元素
 23         List<Element> listFirst = root.elements();
 24          // 迭代
 25         for (Element e : listFirst) {
 26              // 获取一级子元素的属性值
 27             String path = e.attributeValue("className");
 28              // 根据路径(属性)获取字节码文件
 29             Class c = Class.forName(path);
 30              // 获取二级子元素
 31             List<Element> listSecond = e.elements();
 32              // 定义map集合装属性值
 33             Map<String, Object> map = new HashMap<>();
 34              for (Element es : listSecond) {
 35                  // 获取二级子元素的两个属性值
 36                 String name = es.attributeValue("name");
 37                  String value = es.attributeValue("value");
 38                  map.put(name, value);
 39              }
 40              // 利用beanutils工具类进行封装
 41             // 判断是否为person
 42              if (path.matches(".*Person$")) {
 43                  BeanUtils.populate(p, map);
 44              } else {
 45                  BeanUtils.populate(u, map);
 46              }
 47          }
 48          System.out.println(p);
 49          System.out.println(u);
 50      }
 51 
 52 }
 53 

原文地址:https://www.cnblogs.com/huguangqin/p/7118628.html