我正在尝试使用Java验证约束(@ NonNull,@ Min等)来改进和简化部分代码,但是在我的代码中有一种重复出现的情况,我无法弄清楚如何使用约束注释。
这里是一个例子:
public class ResourceIdentifier {
public enum ResourceType { ARTICLE, USER, COMMENT }
private @Getter @Setter String id;
private @Getter @Setter ResourceType type;
}
然后,我想验证MyCommand对象,以便resourceId
不为null,并且resourceId.type
只能是ARTICLE
或COMMENT
。
public class MyCommand {
@NotNull
@Validate(path="#resourceId.type", values={ResourceIdentifier.ResourceType.ARTICLE, ResourceIdentifier.ResourceType.COMMENT})
private ResourceIdentifier resourceId;
(...)
}
我相信我可以通过自定义约束验证注释和反射来实现。
还有其他简单的方法吗?
编辑:想象一下,我还有10-20个其他的命令类,它们需要类型相同的验证resourceId.type = {}
答案 0 :(得分:0)
您可以仅使用断言约束(这是MyCommand
内部的方法):
@AssertTrue(message="Only Comment and Article are allowed as resource type")
public boolean isResourceIdValid() {
return this.resourceId.getType() == ResourceIdentifier.ResourceType.ARTICLE
|| this.resourceId.getType() == ResourceIdentifier.ResourceType.COMMENT;
}