在编写任何应用程序时,确保传入的参数有效是非常关键的。参数校验可以帮助开发者:
NullPointerException
)。assert
关键字assert
关键字可以用来在开发阶段检测代码中的假设是否成立。然而,在生产环境中通常会关闭断言功能,因此这种方法不适合用于最终部署的版本。
示例代码:
public class AssertExample {
public static void main(String[] args) {
assert args.length == 1 : "Exactly one argument expected!";
System.out.println("Argument: " + args[0]);
}
}
Objects.requireNonNull
Objects.requireNonNull
方法可以用来确保传递给方法或构造函数的参数不是null
。
示例代码:
import java.util.Objects;
public class RequireNonNullExample {
public static void main(String[] args) {
String name = null;
try {
greetUser(name);
} catch (NullPointerException e) {
System.err.println(e.getMessage());
}
}
public static void greetUser(String name) {
name = Objects.requireNonNull(name, "Name cannot be null.");
System.out.println("Hello, " + name + "!");
}
}
创建自定义异常类来处理特定的参数错误,可以更加精确地描述错误情况。
示例代码:
public class CustomExceptionExample {
public static void main(String[] args) {
try {
validateAge(-1);
} catch (InvalidAgeException e) {
System.err.println(e.getMessage());
}
}
public static void validateAge(int age) throws InvalidAgeException {
if (age < 0) {
throw new InvalidAgeException("Age cannot be negative.");
}
System.out.println("Age is valid.");
}
static class InvalidAgeException extends IllegalArgumentException {
public InvalidAgeException(String message) {
super(message);
}
}
}
Preconditions
类Guava库提供的Preconditions
类包含了多个静态方法来校验参数,适用于复杂的校验逻辑。
示例代码:
import com.google.common.base.Preconditions;
public class PreconditionsExample {
public static void main(String[] args) {
int number = -5;
try {
checkPositive(number);
} catch (IllegalArgumentException e) {
System.err.println(e.getMessage());
}
}
public static void checkPositive(int number) {
Preconditions.checkArgument(number > 0, "Number must be positive.");
System.out.println("Number is positive.");
}
}
Hibernate Validator允许通过注解来声明参数应该满足的条件,适合用于复杂的业务逻辑。
示例代码:
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
public class ValidatorExample {
public static void main(String[] args) {
User user = new User();
user.setName(null);
user.setAge(-1);
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<User>> violations = validator.validate(user);
for (ConstraintViolation<User> violation : violations) {
System.err.println(violation.getMessage());
}
}
public static class User {
@NotNull
private String name;
@Min(0)
private int age;
// Getters and setters
}
}
Spring框架提供了完整的验证功能,可通过@Valid和@Validated注解进行参数校验。
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import javax.validation.Valid;
public class UserController {
@PostMapping("/user")
public UserResponse createUser(@Valid @RequestBody UserRequest user) {
// 校验通过后执行代码
...
}
}
public class UserRequest {
@NotNull(message = "User name is required.")
private String name;
}
使用Bean Validation注解可以方便地对字段进行校验,如@NotNull、@Size、@Pattern等。
public class Book {
@NotNull(message = "Title cannot be null.")
@Size(min = 5, max = 100, message = "Title length should be between 5 and 100 characters.")
private String title;
// Getter和Setter
}
Validate类提供了多个校验方法,如validateTrue、validateFalse、validateInRange等。
import org.apache.commons.lang3.Validate;
public void calculate(int value) {
Validate.inclusiveBetween(0, 100, value, "Value should be between 0 and 100 inclusive.");
// 正常执行代码
}