0%

BeanUtils

概述:一个可以简化封装数据时繁琐操作的工具类

使用:

  1. 加载jar包(本文使用maven)在pom文件中加入
    1
    2
    3
    4
    5
    <dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.9.3</version>
    </dependency>
  2. 定义一个标准类(这里使用了Lombok)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    import lombok.Getter;
    import lombok.Setter;
    import lombok.ToString;

    @ToString
    public class User {
    @Getter@Setter
    private int id;
    @Getter@Setter
    private String username;
    @Getter@Setter
    private String password;
    }

    用法

  3. 使用populate将map中数据封装到JavaBean中
    1
    2
    3
    4
    5
    public void function() throws ClassNotFoundException, InvocationTargetException, IllegalAccessException {
    User user = new User();
    Map<String,String> map = new HashMap<>();
    BeanUtils.populate(user,map);
    }/*注意key的值要一致*/
  4. 使用setproperty为JavaBean对象赋值
    1
    2
    3
    4
    5
    public void function() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
    Object bean = Class.forName("itcast.domain.User").getDeclaredConstructor().newInstance();
    BeanUtils.setProperty(bean,"username","张三");
    BeanUtils.setProperty(bean,"password","123456");
    }
  5. 使用getproperty来获取JavaBean对象的键值
    1
    2
    3
    4
    5
    6
    7
    public void function() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
    Object bean = Class.forName("itcast.domain.User").getDeclaredConstructor().newInstance();
    String username = BeanUtils.getProperty(bean, "username");
    String password = BeanUtils.getProperty(bean, "password");
    BeanUtils.setProperty(bean,"username","张三");
    BeanUtils.setProperty(bean,"password","123456");
    }
  6. 将bean中的值放入Map中
    1
    2
    3
    4
    public void function()throws Exception{
    Object bean = Class.forName("itcast.domain.User").getDeclaredConstructor().newInstance();
    Map<String, String> map = BeanUtils.describe(bean);
    }
  7. 两个JavaBean对象之间的赋值
    1
    2
    3
    4
    5
    6
    7
    8
    public void function()throws Exception{
    User user1 = new User();
    user1.setPassword("123456");
    user1.setUsername("张三");
    User user2 = new User();
    BeanUtils.copyProperties(user2,user1);
    System.out.println(user2.toString());
    }
    本文只列举了常用的几种用法,其他内容详见官方API文档