【发布时间】:2011-11-03 10:45:20
【问题描述】:
如果至少有一个值(RowFilter 中的值 == 值,条目中的值)是小数,则会发生这种情况。这是一个失败的测试:
@Test
public void testRowFilterNumberMixCore() {
TestEntry entry = new TestEntry(1.2f);
RowFilter filter = RowFilter.numberFilter(ComparisonType.AFTER, 1, 0);
assertTrue(entry + "must be included " + filter, filter.include(entry));
}
输出是:
junit.framework.AssertionFailedError: [entry: 1.2] 必须包含 [RowFilter: ComparisonType = AFTER, compatibleValue: 1, compatibleClass: class java.lang.Integer]原因是 NumberFilter 回退到通过它们的 number.longValue() 比较数字,如果它们不是同一个类(并且可以相互比较)
知道这个细节,测试失败并不令人惊讶(事后看来,不会想到这是一个问题 ;-) 一个级别的防御是确保 - 在客户端代码中 - 要比较的数字 是同一类。这并不总是可能的(想想 f.i.: a tableColumn with columnClass Number)所以我想知道是否/如何改进后备。比如:
if (one instanceof Comparable && one.getClass() == other.getClass()) {
// same class, use comparator
return ((Comparable) one).compareTo(other);
}
if (areIntegers(one, other)) {
// all integers, use longValue
return longCompare(one, other);
}
if (areDecimals(one, other)) {
// anything to do here?
}
// at last resort convert to BigDecimal and compare those:
BigDecimal bigOne = new BigDecimal(one.toString());
BigDecimal bigOther = new BigDecimal(other.toString());
return bigOne.compareTo(bigOther);
这样做可以使测试通过 - 我对隐藏的(阅读:我不知道 :) 的陷阱有点警惕。任何警告/替代方案都非常欢迎!
仅供参考:交叉发布到OTN's Swing forum
跟进
如上所述实施,现在等待客户投诉 - 在这种情况下,将指责所有没有在这里警告我的人 :-)
【问题讨论】:
-
我可以看到 ???? stackoverflow.com/questions/6187566/… ???与否
-
@mKorbel - 感谢您的链接。如果我正确理解了这个问题,看起来有点不相关:如果列类与 getColumnClass 中保证的类不同,格式化程序就会吠叫。我认为这非常值得期待。这归结为简单的数字比较,仅在背景中的表格(自然是明显的目标区域之一:-)
标签: java swing numbers compare rowfilter