I'm trying to improve and simplify part of my code using Java Validation constraint (@NonNull, @Min, etc...) but there is one recurrent case in my code where I can't figure out how to use constraint annotation.
Here is an example:
public class ResourceIdentifier {
public enum ResourceType { ARTICLE, USER, COMMENT }
private @Getter @Setter String id;
private @Getter @Setter ResourceType type;
}
Then I would like to validate MyCommand object so resourceId
is not null and resourceId.type
can only be ARTICLE
or COMMENT
.
public class MyCommand {
@NotNull
@Validate(path="#resourceId.type", values={ResourceIdentifier.ResourceType.ARTICLE, ResourceIdentifier.ResourceType.COMMENT})
private ResourceIdentifier resourceId;
(...)
}
I believe I can achieve this with a custom constraint validation annotation and reflection.
Is there any other simple way ?
EDIT: Imagine I have 10-20 others Command class requiring the type same validation resourceId.type = {}
You can just use an assertion constraint (this is a method inside 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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.