ソースを参照

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

Luguoming 5 年 前
コミット
cab34df313

+ 15 - 0
hutool-core/src/main/java/cn/hutool/core/bean/BeanUtil.java

@@ -618,6 +618,21 @@ public class BeanUtil {
 		copyProperties(source, target, CopyOptions.create());
 		copyProperties(source, target, CopyOptions.create());
 		return target;
 		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对象属性
 	 * 复制Bean对象属性

+ 10 - 0
hutool-core/src/test/java/cn/hutool/core/bean/BeanUtilTest.java

@@ -380,6 +380,16 @@ public class BeanUtilTest {
 		Assert.assertEquals(info.getBookID(), entity.getBookId());
 		Assert.assertEquals(info.getBookID(), entity.getBookId());
 		Assert.assertEquals(info.getCode(), entity.getCode2());
 		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
 	@Data
 	public static class Food {
 	public static class Food {