Java:BeanMap

BeanMap

  • 将对象转为Map
  • 将Map转为对象

BeanMap是Spring封装的一个工具类,用来实现对象与Map的相互转换

将对象转为Map

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cglib.beans.BeanMap;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class MyTest {
    public static void main(String[] args) {
        User user = new User();
        user.setName("赵大土");
        user.setAge(27);
        user.setPhone("123456789");
        BeanMap beanMap = BeanMap.create(user);
        log.info("对象转Map:{}", beanMap);
    }
}

@Data
class User {
    private String name;
    private int age;
    private String phone;
}

将Map转为对象

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cglib.beans.BeanMap;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class MyTest {
    public static void main(String[] args) {
        User user = new User();
        BeanMap beanMap = BeanMap.create(user);
        Map<String, String> map = new HashMap<>();
        map.put("name", "赵大士");
        beanMap.putAll(map);
        log.info("Map转对象{}", user);
    }
}

@Data
class User {
    private String name;
    private Integer age;
    private String phone;
}

你可能感兴趣的:(java,spring)