Groovy: how to test if a property access will be successful?
48,737
Solution 1
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.
Solution 2
I do this in my Gradle scripts:
if(project.hasProperty("propertyThatMightExist")){
use(propertyThatMightExist)
}
Solution 3
If you're doing it on lots of foos and bars you could write (once, but before foo is created):
Object.metaClass.getPropertySafe =
{ delegate.hasProperty(it)?.getProperty(delegate) }
Then you can write:
foo.getPropertySafe('bar')
Solution 4
This worked for me :
Customer.metaClass.properties.find{it.name == 'propertyName'}.
Customer in this example is a domain class. Not sure if it will work for a plain Groovy class
Related videos on Youtube
Author by
fernacolo
Updated on March 20, 2020Comments
-
fernacolo about 4 years
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*/) { use(foo.bar) }
-
fernacolo almost 13 yearsYes, I thought that. But I prefer using exception handling for actual exceptions, because it's more debugger-friendly. Thanks anyway.
-
Joseph almost 11 yearsThis works very well when you don't have an instance of the class, i.e. are dynamically creating criteria to find your instances.
-
Jesse Glick over 8 yearsBeware that this does not work for the case of an undefined variable in the binding, for which you need
binding.hasVariable(variableName)
. -
Lee Meador about 7 yearsDoes this work on a Map where you can use "object.property" to get the value for the key "property"?
-
jaco0646 over 4 yearsAlso,
Customer.metaClass.getMetaProperty('propertyName')
. -
Adrodoc almost 2 yearsFor me this gives
No signature of method: java.lang.Boolean.getProperty() is applicable for argument types: (String)
. Shouldn't this bedelegate.hasProperty(it) ? getProperty(delegate) : null
?