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

Share:
48,737

Related videos on Youtube

fernacolo
Author by

fernacolo

Updated on March 20, 2020

Comments

  • fernacolo
    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
    fernacolo almost 13 years
    Yes, I thought that. But I prefer using exception handling for actual exceptions, because it's more debugger-friendly. Thanks anyway.
  • Joseph
    Joseph almost 11 years
    This 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
    Jesse Glick over 8 years
    Beware that this does not work for the case of an undefined variable in the binding, for which you need binding.hasVariable(variableName).
  • Lee Meador
    Lee Meador about 7 years
    Does this work on a Map where you can use "object.property" to get the value for the key "property"?
  • jaco0646
    jaco0646 over 4 years
    Also, Customer.metaClass.getMetaProperty('propertyName').
  • Adrodoc
    Adrodoc almost 2 years
    For me this gives No signature of method: java.lang.Boolean.getProperty() is applicable for argument types: (String). Shouldn't this be delegate.hasProperty(it) ? getProperty(delegate) : null?