雖然我在這里使用 Hamcrest 庫(kù),但它可能不是 Hamcrest 問(wèn)題而是純 Java ...我有以下方法:public static void isGreaterThan(int valueToValidate, int minExpectedVal) {
MatcherAssert.assertThat(valueToValidate, greaterThan(minExpectedVal));
}我想將其概括為:public static <T> void isGreaterThan(T valueToValidate, T minExpectedVal) {
MatcherAssert.assertThat(valueToValidate, greaterThan(minExpectedVal));
}或者public static void isGreaterThan(Number valueToValidate, Number minExpectedVal) {
MatcherAssert.assertThat(valueToValidate, greaterThan(minExpectedVal));
}Hamcrest 大于簽名是:<T extends Comparable<T>> Matcher<T> greaterThan(T value)和 assertThat 簽名:<T> void assertThat(T actual, Matcher<? super T> matcher)但是,在這兩種情況下,我都在 minExpectedVal 上收到錯(cuò)誤消息,說(shuō)它不能作為 T 應(yīng)用。我怎樣才能克服這個(gè)?
1 回答

拉莫斯之舞
TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超10個(gè)贊
您需要為您的通用版本添加一個(gè)綁定。
public static <T extends Comparable<T>> void isGreaterThan(T valueToValidate, T minExpectedVal) { MatcherAssert.assertThat(valueToValidate, greaterThan(minExpectedVal)); }
請(qǐng)注意,Number
s不可比較;你可以為他們做
public static void isGreaterThan(Number valueToValidate, Number minExpectedVal) { MatcherAssert.assertThat(valueToValidate.doubleValue(), greaterThan(minExpectedVal.doubleValue())); }
編輯:Torben 是正確的,doubleValue()
不一定是無(wú)損的。但是,唯一Number
不是它的標(biāo)準(zhǔn)子類(lèi)型是Long
,BigInteger
和BigDecimal
, 因此您可以明確地檢查它們。但是無(wú)論哪種方式,通用版本都更好。
添加回答
舉報(bào)
0/150
提交
取消