在Groovy中检查Integer是否为Null或数字?

前端之家收集整理的这篇文章主要介绍了在Groovy中检查Integer是否为Null或数字?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个服务方法,如果方法参数为null / blank或不是数字,则必须抛出错误.

调用者发送一个Integer值但在被调用方法中如何检查它是数字还是null.

例如:

  1. def add(value1,value2){
  2. //have to check value1 is null/blank
  3. //check value1 is numeric
  4.  
  5. }
  6.  
  7. caller: class.add(10,20)

任何建议都将不胜感激.

解决方法

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

  1. def isValidInteger(value) {
  2. value.toString().isInteger()
  3. }
  4.  
  5. assert !isValidInteger(null)
  6. assert !isValidInteger('')
  7. assert !isValidInteger(1.7)
  8. assert isValidInteger(10)

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

  1. assert !isValidInteger('10') // FAILS

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

  1. def isValidInteger(value) {
  2. value instanceof Integer
  3. }

猜你在找的Groovy相关文章