在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工作流的參數校驗。請根據實際項目需求進行調整。