Java中BeanUtils使用

BeanUtils使用

BeanUtils提供了对于符合JavaBean规范的实体类进行赋值,取值,拷贝操作的一系列方法,可以自动完成数据类型转换,方便开发者在数据交互中使用。
所有的方法都是静态方法
三个方法
   1. 赋值指定成员变量对应数据
       a. 符合JavaBean规范的类对象
       b. 指定成员变量的名字
       c. Object类型数据用于赋值成员变量

   2. 取值指定成员变量的数据
       a. 符合JavaBean规范的类对象
        b. 指定成员变量的名字
        返回值是对应当前成员变量的数据类型

   3. 拷贝符合JavaBean规范的两个对象数据
        a. 符合JavaBean规范的目标类对象
        b. 符合JavaBean规范的目标数据源对象

    4. 真香方法,从Map双边对联中匹配赋值数据到符合JavaBean规范的类对象
        a. 符合JavaBean规范的类对象
       b. Map双边队列

代码示例:
user表里存在id,userName,password字段

import com.qfedu.a_statement.User;
import org.apache.commons.beanutils.BeanUtils;
import org.junit.Test;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;

/**
 * BeanUtils测试
 *
 * @author Anonymous 2020/3/24 15:09
 */
public class Demo1 {
    @Test
    public void testSetProperty()
            throws InvocationTargetException, IllegalAccessException {
        User user = new User();

        // 给符合JavaBean规范的指定成员变量赋值操作
        BeanUtils.setProperty(user, "id", "123");
        BeanUtils.setProperty(user, "userName", "嘟嘟");
        BeanUtils.setProperty(user, "password", 123456);

        System.out.println(user);
    }

    @Test
    public void testGetProperty()
            throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        User user = new User(1, "嘟嘟", "2344567");

        System.out.println(BeanUtils.getProperty(user, "id"));
        System.out.println(BeanUtils.getProperty(user, "userName"));
        System.out.println(BeanUtils.getProperty(user, "password"));
    }

    @Test
    public void testCopyProperties() throws InvocationTargetException, IllegalAccessException {
        User user = new User(1, "嘟嘟", "2344567");
        User user1 = new User();

        System.out.println("before:" + user1);
        BeanUtils.copyProperties(user1, user);

        System.out.println("after:" + user1);
    }

    // populate
    // 我想表达这个方法真香所以用真香命名,皮一下
    @Test
    public void 真香() throws InvocationTargetException, IllegalAccessException {
        HashMap<String, Integer> map = new HashMap<>();

        map.put("userName", 100);
        map.put("location:", 1);
        map.put("password", 1111);
        map.put("id", 2);

        User user = new User();

        System.out.println("before:" + user);
        BeanUtils.populate(user, map);

        System.out.println("after:" + user);

    }
}

发布了32 篇原创文章 · 获赞 72 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_44945658/article/details/105077682