TP_*_*AVA 4 groovy integer numbers
我有一个服务方法,如果方法参数为null/blank或不是数字,则必须抛出错误.
调用者发送一个Integer值但在被调用方法中如何检查它是数字还是null.
例如:
def add(value1,value2){
//have to check value1 is null/blank
//check value1 is numeric
}
caller: class.add(10,20)
Run Code Online (Sandbox Code Playgroud)
任何建议都将不胜感激.
更具体的是丹克鲁兹的答案,你可以用String.isInteger()方法:
def isValidInteger(value) {
value.toString().isInteger()
}
assert !isValidInteger(null)
assert !isValidInteger('')
assert !isValidInteger(1.7)
assert isValidInteger(10)
Run Code Online (Sandbox Code Playgroud)
但是如果我们传递一个String类似于Integer我们方法的东西会发生什么:
assert !isValidInteger('10') // FAILS
Run Code Online (Sandbox Code Playgroud)
我认为最简单的解决方案是使用instanceof运算符,所有断言都是有效的:
def isValidInteger(value) {
value instanceof Integer
}
Run Code Online (Sandbox Code Playgroud)
你可以尝试使用Groovy的String.isNumber()方法。
例如:
if (value1.isNumber()) ...
if (value2.isNumber()) ...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19344 次 |
| 最近记录: |