BeanUtils.copyProperties进行对象之间的属性赋值

介绍了对象之间的赋值,以及List<>对象之间的赋值

public class User {
	private String name;
	private Integer age;
	public User(String name, Integer age) {
		super();
		this.name = name;
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
}
public class Emp {
	private String name;
	private Integer age;
	private String dept;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public String getDept() {
		return dept;
	}
	public void setDept(String dept) {
		this.dept = dept;
	}
}
import java.util.Arrays;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeansException;
import com.google.common.collect.Lists;
import com.uboxol.cloud.util.BeanUtils;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class HyfUtils {
	/**
     * 对象属性拷贝
     * 将源对象的属性拷贝到目标对象
     *
     * @param source 源对象
     * @param target 目标对象
     */
    public static void copyProperties(Object source, Object target) {
        try {
            BeanUtils.copyProperties(source, target);
        } catch (BeansException e) {
        	logger.error("BeanUtil property copy  failed :BeansException", e);
        } catch (Exception e) {
        	logger.error("BeanUtil property copy failed:Exception", e);
        }
    }
    
    /**
     * @param input 输入集合
     * @param clzz  输出集合类型
     * @param <E>   输入集合类型
     * @param <T>   输出集合类型
     * @return 返回集合
     */
    public static <E, T> List<T> convertList2List(List<E> input, Class<T> clzz) {
	    List<T> output = Lists.newArrayList();
	    if (CollectionUtils.isNotEmpty(input)) {
	        for (E source : input) {
	            T target = BeanUtils.instantiate(clzz);
	            BeanUtils.copyProperties(source, target);
	            output.add(target);
	        }
	    }
	    return output;
	}
    
    public static void main(String[] args) {
    	User u = new User("xiaohong",3);
    	User u2 = new User("lili",4);
    	Emp e = new Emp();
    	
    	HyfUtils.copyProperties(u, e);
    	System.out.println(e.getName());
    	List<User> list = Arrays.asList(u,u2);
    	List<Emp> ee = HyfUtils.convertList2List(list, Emp.class);
    	System.out.println(ee.get(1).getName());
	}

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值