检查 Integer 在 groovy 中是 Null 还是数字?

Posted

技术标签:

【中文标题】检查 Integer 在 groovy 中是 Null 还是数字?【英文标题】:check if Integer is Null or numeric in groovy? 【发布时间】:2012-05-16 04:58:13 【问题描述】:

我有一个服务方法,如果方法参数为空/空白或不是数字,则必须抛出错误。

调用者正在发送一个整数值,但在被调用方法中如何检查它是数字还是空值。

例如:

def add(value1,value2)
 //have to check value1 is null/blank
 //check value1 is numeric



caller: class.add(10,20)

如有任何建议,我们将不胜感激。

【问题讨论】:

【参考方案1】:

更具体的answer of Dan Cruz,可以使用String.isInteger()方法:

def isValidInteger(value) 
    value.toString().isInteger()


assert !isValidInteger(null)
assert !isValidInteger('')
assert !isValidInteger(1.7)
assert isValidInteger(10)

但是如果我们为我们的方法传递一个看起来像 IntegerString 会发生什么:

assert !isValidInteger('10')  // FAILS

我认为最简单的解决方案是使用instanceof 运算符,所有断言都有效:

def isValidInteger(value) 
    value instanceof Integer

【讨论】:

它很好的例子,但断言 isValidInteger('10') 应该是正确的,b'z 他们可能会在 String 对象中发送 Integer,在这种情况下 value instanceof Integer 对我不起作用。【参考方案2】:

您始终可以定义参数的类型:

Number add( Number value1, Number value2 ) 
  value1?.plus( value2 ?: 0 ) ?: value2 ?: 0


int a = 3
Integer b = 4
assert add(    a, null ) == 3
assert add( null,    3 ) == 3
assert add( null, null ) == 0
assert add(    a,    b ) == 7
assert add(    a,    4 ) == 7
assert add(    0,    a ) == 3
assert add(    1,    1 ) == 2
assert add(    0,    0 ) == 0
assert add(   -1,    2 ) == 1

【讨论】:

【参考方案3】:

您可以尝试使用 Groovy 的 String.isNumber() 方法。

例如:

if (value1.isNumber()) ...
if (value2.isNumber()) ...

【讨论】:

但是我得到的是 int 值,我不能在 int 值上做。 Groovy 不使用原始类型;你的意思是Integer?你可以使用if (!value1 || !value1.toString().isNumber()) ... else ...。有关 Groovy 中的 true/false 评估的更多信息,请参阅 Groovy Truth。 谢谢丹,!value1.toString().isNumber()) 成功了..是的..仅指整数。

以上是关于检查 Integer 在 groovy 中是 Null 还是数字?的主要内容,如果未能解决你的问题,请参考以下文章

>> 和 1* 在这个 groovy 语句中是啥意思?

Groovy在英文中是啥意思

integer在c语言中是啥意思

使用 Groovy 检查对象是不是在集合中

Groovy集合遍历 ( 使用集合的 eachWithIndex 方法进行遍历 | 代码示例 )

Groovy文件检查