diff --git a/hutool-core/src/main/java/cn/hutool/core/lang/Assert.java b/hutool-core/src/main/java/cn/hutool/core/lang/Assert.java index ec0b69b27..9f21ff305 100644 --- a/hutool-core/src/main/java/cn/hutool/core/lang/Assert.java +++ b/hutool-core/src/main/java/cn/hutool/core/lang/Assert.java @@ -539,6 +539,68 @@ public class Assert { return noNullElements(array, "[Assertion failed] - this array must not contain any null elements"); } + /** + * 断言给定集合为空 + * 并使用指定的函数获取错误信息返回 + *
+	 * Assert.empty(collection, ()->{
+	 *      // to query relation message
+	 *      return new IllegalArgumentException("relation message to return");
+	 *  });
+	 * 
+ * + * @param 集合元素类型 + * @param 集合类型 + * @param 异常类型 + * @param collection 被检查的集合 + * @param errorSupplier 错误抛出异常附带的消息生产接口 + * @throws X if the collection is not {@code null} or has elements + * @see CollUtil#isEmpty(Iterable) + * @since 5.8.39 + */ + public static , X extends Throwable> void empty(T collection, Supplier errorSupplier) throws X { + if (CollUtil.isNotEmpty(collection)) { + throw errorSupplier.get(); + } + } + + + /** + * 断言给定集合为空 + * + *
+	 * Assert.empty(collection, "Collection must have no elements");
+	 * 
+ * + * @param 集合元素类型 + * @param 集合类型 + * @param collection 被检查的集合 + * @param errorMsgTemplate 异常时的消息模板 + * @param params 参数列表 + * @throws IllegalArgumentException if the collection is not {@code null} or has elements + * @since 5.8.39 + */ + public static > void empty(T collection, String errorMsgTemplate, Object... params) throws IllegalArgumentException { + empty(collection, () -> new IllegalArgumentException(StrUtil.format(errorMsgTemplate, params))); + } + + /** + * 断言给定集合为空 + * + *
+	 * Assert.empty(collection);
+	 * 
+ * + * @param 集合元素类型 + * @param 集合类型 + * @param collection 被检查的集合 + * @throws IllegalArgumentException if the collection is not {@code null} or has elements + * @since 5.8.39 + */ + public static > void empty(T collection) throws IllegalArgumentException { + empty(collection, "[Assertion failed] - this collection must be empty"); + } + /** * 断言给定集合非空 * 并使用指定的函数获取错误信息返回 diff --git a/hutool-core/src/test/java/cn/hutool/core/lang/AssertTest.java b/hutool-core/src/test/java/cn/hutool/core/lang/AssertTest.java index 63b73eb5a..337f437f4 100755 --- a/hutool-core/src/test/java/cn/hutool/core/lang/AssertTest.java +++ b/hutool-core/src/test/java/cn/hutool/core/lang/AssertTest.java @@ -4,6 +4,9 @@ import cn.hutool.core.util.StrUtil; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; +import java.util.ArrayList; +import java.util.List; + public class AssertTest { @Test @@ -68,4 +71,13 @@ public class AssertTest { } + @Test + public void emptyCollectionTest() { + List testList = new ArrayList<>(); + Assertions.assertDoesNotThrow(() -> Assert.empty(null)); + Assertions.assertDoesNotThrow(() -> Assert.empty(testList)); + testList.add(new Object()); + Assertions.assertThrows(IllegalArgumentException.class, () -> Assert.empty(testList)); + } + }