我想知道在使用CsvRoutines包时是否有检查和验证字段的方法。基本上,如果第一列只有数字,我想要处理行,然后跳过/可能抛出异常。我猜在2.7.0中发布的@Validate注释可以用来实现这一点。但我想知道,在2.5.9这样的早期版本中,是否还有其他方法来实现同样的目标?
发布于 2018-09-21 06:34:53
这里图书馆的作者。除了更新到最新版本之外,没有别的方法了。有什么特别的原因不能升级吗?
更新:您可以将@Parsed注释放在类的getter或setter上,并在其中执行验证。这可能是最干净的方法。例如:
class Test {
private Integer number;
//accepts a String here... so this is straight from the parser before it tries to convert anything into an integer - which lets you validate or throw a custom exception
@Parsed
void setNumber(String number){
try{
this.number = Integer.valueOf(number);
} catch(NumberFormatException e){
throw new IllegalArgumentException(number + " is not a valid integer");
}
}
}另一种选择是使用自定义转换类。复制在最新版本中使用的类ValidatedConversion的代码,然后创建以下子类:
public static class RangeLimiter extends ValidatedConversion {
int min;
int max;
public RangeLimiter(String[] args) {
super(false, false); //not null, not blank
min = Integer.parseInt(args[0]);
max = Integer.parseInt(args[1]);
}
protected void validate(Object value) {
super.validate(value); //runs the existing validations for not null and not blank
int v = ((Number) value).intValue();
if (v < min || v > max) {
throw new DataValidationException("out of range: " + min + " >= " + value + " <=" + max);
}
}
}现在,在您的代码中,使用以下代码:
@Parsed(field = "number")
@Convert(conversionClass = RangeLimiter.class, args = {"1", "10"}) //min = 1, max = 10
public int number;我没有用旧版本来测试这个。我认为您可能需要在applyDefaultConversion=false注释中设置标志@Parsed,并使您的转换类在运行验证时将String转换为int。
总之,这是相当多的工作,只要升级到最新版本就可以很容易地避免。
https://stackoverflow.com/questions/52433947
复制相似问题