com.soento.core.util.BeanUtil Maven / Gradle / Ivy
package com.soento.core.util;
import com.soento.core.lang.Pojo;
import org.apache.commons.beanutils.BeanUtils;
import java.util.Iterator;
import java.util.Map;
/**
* @author soento
*/
public class BeanUtil extends BeanUtils {
public static void copy(Object from, Object to) {
if (from == null) {
return;
}
if (to == null) {
throw new RuntimeException("目标拷贝对象不能为空");
}
Pojo fObj = Pojo.build(from);
Pojo tObj = Pojo.build(to);
Iterator> it = tObj.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = it.next();
if (fObj.hasField(entry.getKey())) {
entry.setValue(fObj.get(entry.getKey()));
}
}
// 覆盖to
to = tObj.toObject(to.getClass());
}
/**
* 对象构建
*
* @param from 拷贝源
* @param clazz 目标类
* @param 目标类泛型
* @return 结果对象
*/
public static T build(Object from, Class clazz) {
if (from == null) {
return null;
}
String json = JsonUtil.toJson(from);
return JsonUtil.toObject(json, clazz);
}
}