fernacolo fernacolo - 1 year ago 93
Groovy Question

Groovy: how to test if a property access will be successful?

I have a variable Object foo, which is not null. I want to use foo.bar, but only if it won't bomb me with 'No such property: bar for class: Whatever'.

How should I do the following test:

if (#test-here#) {

Answer Source

Use object.hasProperty(propertyName). This will return a truthy value (the property reference) if the property exists. Also object.metaClass.hasProperty(instance, propertyName) is possible. Use object.respondsTo(methodName) to test for method existence.

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