Velvet Star Monitor

Standout celebrity highlights with iconic style.

general

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

Writer 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.

2

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

2
boolean 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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy