UniVocity 如何将参数添加到自定义验证器

我正在为单声解析器创建一些自定义验证器,我想添加一些参数,如下所示:


   public class Size implements Validator<String>

   int max;

然后像这样使用它:


   @Parsed

   @Validate(nullable = false, validators = Size.class(8) )

   private String someString;

我没有找到类似的东西或带有注释的示例。


也许使用javax.validation注释?


或者注入使用范围限制构造函数创建的 sizeValidation 对象?


谢谢!


白衣染霜花
浏览 110回答 1
1回答

PIPIONE

这里有两个选项:1 - 在 setter 上添加注释(简单但不可重用:&nbsp; &nbsp; @Parsed&nbsp; &nbsp; @Validate(nullable = false)&nbsp; &nbsp; public void setSomeString(String value){&nbsp; &nbsp; &nbsp; &nbsp; if(value.length() < 3 || value.length() > 5){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw new DataValidationException("SomeString can't have length " + value.length());&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; this.someString = value;&nbsp; &nbsp; }2 - 扩展类并在注释上使用该类:ValidatedConversion@Convertpublic class LengthValidator extends ValidatedConversion {&nbsp; &nbsp; private int min;&nbsp; &nbsp; private int max;&nbsp; &nbsp; public LengthValidator(String... args) {&nbsp; &nbsp; &nbsp; &nbsp; super(false, false); //not null / not blank&nbsp; &nbsp; &nbsp; &nbsp; this.min = Integer.parseInt(args[0]);&nbsp; &nbsp; &nbsp; &nbsp; this.max = Integer.parseInt(args[1]);&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; protected void validate(Object value) {&nbsp; &nbsp; &nbsp; &nbsp; super.validate(value); //let super check for null and whatever you need.&nbsp; &nbsp; &nbsp; &nbsp; String string = value.toString();&nbsp; &nbsp; &nbsp; &nbsp; if(string.length() < min || string.length() > max){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw new com.univocity.parsers.common.DataValidationException("Value can't have length " + string.length());&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}然后将其添加到您的属性中:&nbsp; &nbsp; @Parsed&nbsp; &nbsp; @Convert(conversionClass = LengthValidator.class, args = {"3", "5"})&nbsp; &nbsp; private String someString;希望这有帮助。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java