Groovy: how to test if a property access will be successful?
Sophia Terry
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)
} 6 Answers
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.
I do this in my Gradle scripts:
if(project.hasProperty("propertyThatMightExist")){ use(propertyThatMightExist)
} 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') 1 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
2boolean exist = Person.metaClass.properties.any{it.name == 'propName'}if propName is an attribute ,exist=true // vice versa
I can't speak for Groovy specifically, but in just about every dynamic language I've ever used the idiomatic way of doing this is to just do it, and catch the exception if it gets thrown, and in the exception handler do whatever you need to do to handle the situation sensibly.
1