latvian latvian - 1 year ago 95
Groovy Question

how to avoid missingPropertyException

If object does not have property and i am calling the property, we got 'missingPropertyException'. Can i do something like safe null (?.) the same way for missing properties so it doesn't through exceptions?

Thank You

Answer Source

One option would be:

def result = obj.hasProperty( 'b' ) ? obj.b : null

Which would return null if the object doesn't have the property...

Another would be to add propertyMissing to your class like so:

def propertyMissing( name ) {

This means that any missing properties would just result in null.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download