在Java中,Activity工作流的参数校验可以通过以下几个步骤进行:
public class MyActivityInput {
private String name;
private int age;
// 其他属性和getter/setter方法
}
@NotNull
、@Size
、@Min
、@Max
等注解来限制参数的取值范围。import javax.validation.constraints.*;
public class MyActivityInput {
@NotNull(message = "Name cannot be null")
@Size(min = 1, max = 100, message = "Name must be between 1 and 100 characters")
private String name;
@Min(value = 0, message = "Age must be greater than or equal to 0")
@Max(value = 150, message = "Age must be less than or equal to 150")
private int age;
// 其他属性和getter/setter方法
}
Validator
类对输入参数进行校验。如果校验失败,可以抛出一个自定义的异常,例如ValidationException
。import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;
public class MyActivity {
public void execute(MyActivityInput input) {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<MyActivityInput>> violations = validator.validate(input);
if (!violations.isEmpty()) {
StringBuilder sb = new StringBuilder();
for (ConstraintViolation<MyActivityInput> violation : violations) {
sb.append(violation.getMessage()).append("\n");
}
throw new ValidationException(sb.toString());
}
// 其他业务逻辑
}
}
ValidationException
异常。可以将异常信息显示给用户,或者记录到日志中。public class Main {
public static void main(String[] args) {
MyActivity activity = new MyActivity();
MyActivityInput input = new MyActivityInput();
// 设置输入参数
try {
activity.execute(input);
} catch (ValidationException e) {
System.err.println("Validation failed: " + e.getMessage());
// 处理异常,例如显示错误信息或记录日志
}
}
}
通过以上步骤,可以实现Java Activity工作流的参数校验。请根据实际项目需求进行调整。