I have a service method and have to throw an error if method parameter is null/blank or not numeric.
Caller is sending an Integer value but in called method how to check if it is numeric or null.
ex:
def add(value1,value2){
//have to check value1 is null/blank
//check value1 is numeric
}
caller: class.add(10,20)
Any suggestions around would be appreciated.
Groovy supports integer and floating point numbers. An integer is a value that does not include a fraction.
Groovy adds several methods to the String class to see if the string value is a number. We can check for all kind of number type like Integer , Double , BigDecimal and more.
Groovy supports all Java types (primitive and reference types). All primitives types are auto converted to their wrapper types. So int a = 2 will become Integer a = 2.
More concrete that the answer of Dan Cruz, you can use String.isInteger()
method:
def isValidInteger(value) {
value.toString().isInteger()
}
assert !isValidInteger(null)
assert !isValidInteger('')
assert !isValidInteger(1.7)
assert isValidInteger(10)
But what happens if we pass a String
that looks like a Integer
for our method:
assert !isValidInteger('10') // FAILS
I think that the most simple solution is use the instanceof
operator, all assert are valid:
def isValidInteger(value) {
value instanceof Integer
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With