DoubleRangeFieldValidator的实现和疑问
我们使用IntRangeFieldValidator的比较多,今天看了一下 DoubleRangeFieldValidator这个注解,看到有四个参数 minInclusive,maxInclusive,minExclusive,maxExclusive
有点懵,再看一下它的实现:
现在的疑问是我们发现minInclusiveValue和minExclusiveValue是相关的,为什么我们不能把参数变成这样四个参数呢:
String min = null;
String max = null;
boolean includeMin = true;
boolean includeMax = true;
public class DoubleRangeFieldValidator extends FieldValidatorSupport { String maxInclusive = null; String minInclusive = null; String minExclusive = null; String maxExclusive = null; Double maxInclusiveValue = null; Double minInclusiveValue = null; Double minExclusiveValue = null; Double maxExclusiveValue = null; // 这个方法没有什么,主要是把要验证的数转Double,然后在 // 设置那四个参数,最后进行比较。 public void validate(Object object) throws ValidationException { String fieldName = getFieldName(); Double value; try { Object obj = this.getFieldValue(fieldName, object); if (obj == null) { return; } value = Double.valueOf(obj.toString()); } catch (NumberFormatException e) { return; } parseParameterValues(); // 重点来看一下这个实现,如果设置了maxInclusiveValue,那么该值比它大的时候, // 就直接报错,minInclusiveValue道理也是一样的。 maxExclusiveValue实际上是// 判断一下包含。 if ((maxInclusiveValue != null && value.compareTo(maxInclusiveValue) > 0) || (minInclusiveValue != null && value.compareTo(minInclusiveValue) < 0) || (maxExclusiveValue != null && value.compareTo(maxExclusiveValue) >= 0) || (minExclusiveValue != null && value.compareTo(minExclusiveValue) <= 0)) { addFieldError(fieldName, object); } } private void parseParameterValues() { this.minInclusiveValue = parseDouble(minInclusive); this.maxInclusiveValue = parseDouble(maxInclusive); this.minExclusiveValue = parseDouble(minExclusive); this.maxExclusiveValue = parseDouble(maxExclusive); } private Double parseDouble (String value) { if (value != null) { try { return Double.valueOf(value); } catch (NumberFormatException e) { if (log.isWarnEnabled()) { log.warn("DoubleRangeFieldValidator - [parseDouble]: Unable to parse given double parameter " + value); } } } return null; }