Java Bean 转换(copy)
废话不多说上代码
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.util.StringUtils;
import java.beans.PropertyDescriptor;
import java.util.HashSet;
import java.util.Set;
/**
* 实现此接口让对象具有基本属性拷贝的能力
*/
public interface Copier {
/**
* 传入对象,对其进行属性拷贝
*
* @param target 拷贝目标对象
*/
default <T> void copy(T target) {
BeanUtils.copyProperties(this, target);
}
/**
* 传入对象类型, 进行属性拷贝并且得到其对象
*
* @param type 对象类型 Class对象
* @return 对象
*/
default <T> T copy(Class<T> type) {
T target = BeanUtils.instantiateClass(type);
copy(target);
return target;
}
/**
* 不为null的属性值才会拷贝
*
* @param target 拷贝目标对象
*/
default <T> void copyNotNull(T target) {
BeanWrapper wrapper = new BeanWrapperImpl(this);
PropertyDescriptor[] pds = wrapper.getPropertyDescriptors();
Set<String> properties = new HashSet<>();
for (PropertyDescriptor propertyDescriptor : pds) {
String propertyName = propertyDescriptor.getName();
Object propertyValue = wrapper.getPropertyValue(propertyName);
if (propertyValue != null) {
if (propertyValue instanceof String && !StringUtils.hasText((String) propertyValue)) {
properties.add(propertyName);
}
} else {
properties.add(propertyName);
}
}
BeanUtils.copyProperties(this, target, properties.toArray(new String[0]));
properties.clear();
}
}
让自己的实体类实现上面的类,使用方法如下:
创建俩个测试的实体类:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class TestEntity3 implements Copier {
private Integer id;
private String name;
private Integer age;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class TestEntity4 implements Copier {
private Integer id;
private String name;
}
测试:
public class Beanutils {
public static void main(String[] args) {
TestEntity3 testEntity3 = new TestEntity3();
testEntity3.setId(1);
testEntity3.setName("aaa");
testEntity3.setAge(20);
TestEntity4 copy = testEntity3.copy(TestEntity4.class);
System.out.println(copy);
}
}
结果:
结束!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本