如果您想验证 POJO,可以查看 Oval 框架 http://oval.sourceforge.net/
如果您的应用是基于 pojos 或 beans 设计的,JSR-303(及其实现)也可能会有所帮助
以下是 OVal 中的示例自定义验证:
假设您必须验证 SomeValueClass 中的变量映射并确保键“greeting”的值始终存在。
public class SomeValueClass {
@FormCollection
Map variables;
public static void main(String[] args) {
SomeValueClass svc1 = new SomeValueClass();
svc1.variables = new HashMap();
svc1.variables.put("greeting", "");
Validator validator = new Validator();
List<ConstraintViolation> violations = validator.validate(svc1);
System.out.println("svc1 violations.size() = " + violations.size());
}
“映射变量”上的@FormCollection 注释;是一个自定义验证器,如下所示:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@net.sf.oval.configuration.annotation.Constraint(checkWith = FormCollectionCheck.class)
public @interface FormCollection {
String message() default "Some errors in the form";
}
约束检查类将如下所示:
public class FormCollectionCheck extends AbstractAnnotationCheck<FormCollection> {
public boolean isSatisfied(Object validatedObject, Object valueToValidate, OValContext context, Validator validator) {
Map vars = (Map) valueToValidate;
return !(vars.get("greeting")==null || ((String)vars.get("greeting")).length()<=0);
}
}
希望对您有所帮助,
干杯