BeanMap常用方法 - cglib.beans常用工具类

BeanCopier是Cglib包中的一个类,用于对象与Map之间相互转换。

 

实体类

package com.hanyong.domain;

import lombok.Data;

/**
 * SysUserDO
 *
 * @Author: han
 * @CreateTime: 2019-05-28
 */
@Data
public class SysUserDO {
    private String id;
    private String username;
    private String password;
    private String phone;
    private String createdBy;
    private String createdTime;
    private String updatedBy;
    private String updatedTime;
    private String remark;
    private String status;
}

 

Bean 转 Map

package com.hanyong;

import com.hanyong.domain.SysUserDO;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Map;

/**
 * MybatisTest
 *
 * @Author: hanYong
 * @CreateTime: 2019-05-25
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = HyProjectApplication.class)
public class MybatisTest {


    @Test
    public void test01() {
        SysUserDO sysUserDO = new SysUserDO();
        sysUserDO.setId("123");
        sysUserDO.setUsername("hanyong");
        BeanMap beanMap = BeanMap.create(sysUserDO);
        Map map1 = getMap(beanMap);
        System.out.println(map1.toString());
        // 结果:{id=123, status=null, username=hanyong, updatedTime=null, password=null, updatedBy=null, createdBy=null, phone=null, createdTime=null, remark=null}

    }

    public Map getMap(BeanMap beanMap){
        return beanMap;
    }
}

 

beanMap的底层是实现了Map,所以可以转换为Map类型

            BeanMap常用方法 - cglib.beans常用工具类_第1张图片

 

注意:Bean的修改和新增会直接影响beanMap,如果使用删除,则会报错

SysUserDO sysUserDO = new SysUserDO();
sysUserDO.setId("123");
sysUserDO.setUsername("hanyong");
BeanMap beanMap = BeanMap.create(sysUserDO);
sysUserDO.setUsername("张三"); // bean修改直接影响BeanMap
beanMap.remove("Id"); // 如果使用删除,会抛出java.lang.UnsupportedOperationException


Map 转 Bean

SysUserDO sysUserDO = new SysUserDO();
BeanMap beanMap = BeanMap.create(sysUserDO);

Map map = new HashMap<>();
map.put("id", "123");
map.put("username", "hanyong");

beanMap.putAll(map);

System.out.println(sysUserDO.toString());
// SysUserDO(id=123, username=hanyong, password=null, phone=null, createdBy=null, createdTime=null, updatedBy=null, updatedTime=null, remark=null, status=null)

 

你可能感兴趣的:(「,常用工具类,(Util),」)