本文目录导读:

- 基础手动校验
- 使用Apache Commons Collections
- Spring框架的Assert工具
- Java 8+ Stream + Optional 的方式
- 自定义集合校验工具类
- 使用Java Bean Validation (JSR 380/Hibernate Validator)
- 通用校验方法(实用推荐)
- 最佳实践建议
在Java中校验集合参数有多种方法,我会从简单到专业为你介绍几种常用方案。
基础手动校验
最直接的方式:
public void processUsers(List<User> users) {
if (users == null) {
throw new IllegalArgumentException("用户列表不能为null");
}
if (users.isEmpty()) {
throw new IllegalArgumentException("用户列表不能为空");
}
if (users.size() > 100) {
throw new IllegalArgumentException("用户列表不能超过100个");
}
// 业务处理...
}
使用Apache Commons Collections
import org.apache.commons.collections4.CollectionUtils;
public void processUsers(List<User> users) {
// 检查null或空集合
if (CollectionUtils.isEmpty(users)) {
throw new IllegalArgumentException("用户列表不能为空");
}
// 检查非空
if (CollectionUtils.isNotEmpty(users)) {
// 业务处理
}
}
Spring框架的Assert工具
import org.springframework.util.Assert;
public void processUsers(List<User> users) {
// null检查 + 空值检查
Assert.notEmpty(users, "用户列表不能为空");
// 仅检查null
Assert.notNull(users, "用户列表不能为null");
// 大小检查
Assert.isTrue(users.size() <= 100, "用户列表不能超过100个");
}
Java 8+ Stream + Optional 的方式
import java.util.Optional;
public void processUsers(List<User> users) {
Optional.ofNullable(users)
.filter(list -> !list.isEmpty())
.filter(list -> list.size() <= 100)
.orElseThrow(() -> new IllegalArgumentException("用户列表参数无效"));
// 或使用ifPresent处理
Optional.ofNullable(users)
.filter(list -> !list.isEmpty())
.ifPresentOrElse(
this::processUsers,
() -> { throw new IllegalArgumentException("用户列表不能为空"); }
);
}
自定义集合校验工具类
public class CollectionValidator {
public static <T> void validateCollection(
Collection<T> collection,
CollectionValidationRule... rules) {
if (collection == null) {
throw new IllegalArgumentException("集合不能为null");
}
for (CollectionValidationRule rule : rules) {
rule.validate(collection);
}
}
@FunctionalInterface
public interface CollectionValidationRule {
void validate(Collection<?> collection);
}
// 预定义规则
public static CollectionValidationRule notEmpty() {
return collection -> {
if (collection.isEmpty()) {
throw new IllegalArgumentException("集合不能为空");
}
};
}
public static CollectionValidationRule maxSize(int maxSize) {
return collection -> {
if (collection.size() > maxSize) {
throw new IllegalArgumentException(
"集合大小不能超过" + maxSize);
}
};
}
public static CollectionValidationRule elementNotNull() {
return collection -> {
if (collection.stream().anyMatch(Objects::isNull)) {
throw new IllegalArgumentException("集合元素不能为null");
}
};
}
}
// 使用示例
public void processUsers(List<User> users) {
CollectionValidator.validateCollection(
users,
CollectionValidator.notEmpty(),
CollectionValidator.maxSize(100),
CollectionValidator.elementNotNull()
);
// 业务处理...
}
使用Java Bean Validation (JSR 380/Hibernate Validator)
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;
public class PageRequest {
@NotEmpty(message = "用户列表不能为空")
@Size(max = 100, message = "用户列表不能超过100个")
private List<@Valid User> users;
// getter/setter...
}
// 服务层
@Service
public class UserService {
@Autowired
private Validator validator;
public void processUsers(@Valid PageRequest request) {
Set<ConstraintViolation<PageRequest>> violations =
validator.validate(request);
if (!violations.isEmpty()) {
throw new ConstraintViolationException(violations);
}
// 业务处理...
}
}
// 或者在Controller中使用@Valid
@RestController
public class UserController {
@PostMapping("/users/process")
public void processUsers(@Valid @RequestBody PageRequest request) {
// 自动校验
}
}
通用校验方法(实用推荐)
public class ValidationUtils {
/**
* 校验集合参数
* @param collection 要校验的集合
* @param paramName 参数名称(用于错误信息)
* @param maxSize 允许的最大大小
* @param allowNull 是否允许null
* @param allowEmpty 是否允许为空
* @param <T> 集合类型
*/
public static <T extends Collection<?>> void validateCollection(
T collection,
String paramName,
int maxSize,
boolean allowNull,
boolean allowEmpty) {
// null检查
if (collection == null) {
if (!allowNull) {
throw new IllegalArgumentException(
String.format("%s不能为null", paramName));
}
return;
}
// 空检查
if (collection.isEmpty() && !allowEmpty) {
throw new IllegalArgumentException(
String.format("%s不能为空集合", paramName));
}
// 大小检查
if (collection.size() > maxSize) {
throw new IllegalArgumentException(
String.format("%s大小不能超过%d,当前大小:%d",
paramName, maxSize, collection.size()));
}
}
}
// 使用示例
public void processUsers(List<User> users) {
ValidationUtils.validateCollection(users, "用户列表", 100, false, false);
// 或更简洁的调用
validateUsers(users);
}
private void validateUsers(List<User> users) {
ValidationUtils.validateCollection(users, "用户列表", 100, false, false);
}
最佳实践建议
-
分层校验:
- Controller层:使用@Valid注解进行基本校验
- Service层:进行业务逻辑相关的集合校验
- 工具类:通用校验逻辑抽取
-
错误信息要清晰:
// 好的做法 throw new IllegalArgumentException( String.format("用户列表参数无效:%s,允许范围:1-%d", users == null ? "null" : String.valueOf(users.size()), 100)); -
考虑性能:
// 大批量数据时先检查null和大小 if (users == null || users.size() > 10000) { throw new IllegalArgumentException("参数无效"); } // 再逐个校验元素 users.forEach(this::validateUser);
推荐使用Spring的Assert或Hibernate Validator,因为它们:
- 与主流框架集成度高
- 错误信息清晰
- 支持国际化
- 可以在方法参数上直接使用注解