Spring BeanUtils简单使用

引入包

     <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.9.3</version>
        </dependency>

main执行

package com.gwzx.pay;

import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.beanutils.BeanUtils;

public class S {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
            // 1: 属性复制
            Student2 s1 = new Student2(1, "张三", 18, Boolean.FALSE);
            Student2 s2 = new Student2();
            BeanUtils.copyProperties(s2, s1);
            System.out.println("1:" + s2.getName());

            // 2: 属性放入map
            Map<String, String> map = BeanUtils.describe(s2);
            for (Entry<String, String> o : map.entrySet()) {
                System.out.println(o.getKey() + "=" + o.getValue());
            }
            map.clear();
            // 不会放入s2
            map.put("aa", "bb");
            // 覆盖s2
            map.put("id", "666");
            map.put("bool", "true");

            // 3: Map值 动态放入s2对象中
            BeanUtils.populate(s2, map);
            System.out.println(s2.toString());

        } catch (Exception e) {
            // TODO: handle exception
        }
    }

}
原文地址:https://www.cnblogs.com/eason-d/p/9523073.html