问题
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)
}
回答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.
回答2:
I do this in my Gradle scripts:
if(project.hasProperty("propertyThatMightExist")){
use(propertyThatMightExist)
}
回答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')
回答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
回答5:
boolean exist = Person.metaClass.properties.any{it.name == 'propName'}
if propName is an attribute ,exist=true // vice versa
回答6:
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.
来源:https://stackoverflow.com/questions/5240680/groovy-how-to-test-if-a-property-access-will-be-successful