How to overload some Groovy type conversions to avoid try / catch exceptions of NumberFormatException?

It pains me to encapsulate every asType call asType a try/catch like this:

 def b = "" def c try { c = b as Integer } catch (NumberFormatException) { c = null } println c 

instead, I would like to write the following in my code:

 def b = "" def c = b as Integer 

and if b not well formatted, I want null be assigned c

So, how can I overload this default behavior for the asType operator?

Is it risky if I do this for my entire Grails application? Or is it the best solution to just create your own method (for example, asTypeSafe ) and name it? Do Groovy / Do Grails have some configuration settings regarding Groovy type conversion?

EDIT (for people interested in the implemented answer) Based on the accepted answer, I added the following code to my bootstrap.groovy file and it works great.

 String.metaClass.asTypeSafe = {Class c -> try { delegate.asType(c) } catch (Exception) { return null } } 

and I call it the following:

 def myNum = myStr.asTypeSafe(Integer) 
+7
type-conversion grails groovy
source share
2 answers

You can override the default behavior by providing a new implementation of asType. Make sure you keep the old one and name it for other classes that you do not want to process yourself. Example:

 oldAsType = String.metaClass.getMetaMethod("asType", [Class] as Class[]) String.metaClass.asType = { Class c -> if (c == Integer) { delegate.isInteger() ? delegate.toInteger() : null } else { oldAsType.invoke(delegate, c) } } 

As for whether this is a good idea, just remember that many objects will use strings, and it is possible that they call this conversion and rely on the generated exception. You mess with things at a fairly low level.

Grails domain objects will do a lot of heavy lifting of type conversion if you pass the params object from the controller, but I don't think it has any global settings for this kind of thing.

+9
source share

For those of you who are using Grails 1.2, we now have this option when working with options, and I believe all GrailsParameterMaps files.

 def someInt = params.int("myInt") 

See: http://www.grails.org/1.2+Release+Notes#Convenient%2C%20null%20safe%20converters%20in%20params%20and%20tag%20attributes

+2
source share

All Articles