为了账号安全,请及时绑定邮箱和手机立即绑定

Java - 一种通用的数字方法

Java - 一种通用的数字方法

红糖糍粑 2023-05-24 15:28:08
虽然我在这里使用 Hamcrest 库,但它可能不是 Hamcrest 问题而是纯 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 上收到错误消息,说它不能作为 T 应用。我怎样才能克服这个?
查看完整描述

1 回答

?
拉莫斯之舞

TA贡献1820条经验 获得超10个赞

您需要为您的通用版本添加一个绑定。

public static <T extends Comparable<T>> void isGreaterThan(T valueToValidate, T minExpectedVal) {
    MatcherAssert.assertThat(valueToValidate, greaterThan(minExpectedVal));
}

请注意,Numbers不可比较;你可以为他们做

public static void isGreaterThan(Number valueToValidate, Number minExpectedVal) {
    MatcherAssert.assertThat(valueToValidate.doubleValue(), greaterThan(minExpectedVal.doubleValue()));
}

编辑:Torben 是正确的,doubleValue()不一定是无损的。但是,唯一Number不是它的标准子类型是Long,BigIntegerBigDecimal, 因此您可以明确地检查它们。但是无论哪种方式,通用版本都更好。


查看完整回答
反对 回复 2023-05-24
  • 1 回答
  • 0 关注
  • 97 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信