复制创建一个Bean对象, 并忽略某些属性

This commit is contained in:
Luguoming 2020-06-12 09:04:07 +08:00
parent fd6c023c78
commit cab34df313
2 changed files with 25 additions and 0 deletions

View File

@ -618,6 +618,21 @@ public class BeanUtil {
copyProperties(source, target, CopyOptions.create());
return target;
}
/**
* 按照Bean对象属性创建对应的Class对象并忽略某些属性
*
* @param <T> 对象类型
* @param source 源Bean对象
* @param tClass 目标Class
* @param ignoreProperties 不拷贝的的属性列表
* @return 目标对象
*/
public static <T> T copyProperties(Object source, Class<T> tClass, String... ignoreProperties) {
T target = ReflectUtil.newInstanceIfPossible(tClass);
copyProperties(source, target, CopyOptions.create().setIgnoreProperties(ignoreProperties));
return target;
}
/**
* 复制Bean对象属性

View File

@ -380,6 +380,16 @@ public class BeanUtilTest {
Assert.assertEquals(info.getBookID(), entity.getBookId());
Assert.assertEquals(info.getCode(), entity.getCode2());
}
@Test
public void copyBeanTest(){
Food info = new Food();
info.setBookID("0");
info.setCode("123");
Food newFood = BeanUtil.copyProperties(info, Food.class, "code");
Assert.assertEquals(info.getBookID(), newFood.getBookID());
Assert.assertNull(newFood.getCode());
}
@Data
public static class Food {