有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JavaBean验证程序组件约束

嗨,我想知道如何限制一个字段接受特定的值。假设有一颗豆子

class Student{
    @NotNull
    private int id;
    // Country should be either India or USA
    private String Country;
}

请让我知道,如果您知道任何注释将用于国家/地区字段。谢谢你的帮助


共 (1) 个答案

  1. # 1 楼答案

    就像afzalex所说的,使用枚举来限制选择。可以使用自定义Bean验证约束public @interface CountryConstraint来指定允许的枚举项,然后实现约束验证器public class CountryValidator implements ConstraintValidator<CountryConstraint, Country>来验证值Herehere是如何实现这一点的完整示例