Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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) } 
like image 486
fernacolo Avatar asked Mar 09 '11 02:03

fernacolo


People also ask

How do I run a Groovy test?

Test a Groovy applicationPress Ctrl+Shift+T and select Create New Test. In the dialog that opens, specify your test settings and click OK. Open the test in the editor, add code and press Ctrl+Shift+F10 or right-click the test class and from the context menu select Run 'test name'.

How does assert work in Groovy?

An assertion is similar to an if, it verifies the expression you provide: if the expression is true it continues the execution to the next statement (and prints nothing), if the expression is false, it raises an AssertionError.

What is a property in Groovy?

When a Groovy class definition declares a field without an access modifier, then a public setter/getter method pair and a private instance variable field is generated which is also known as "property" according to the JavaBeans specification.


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

like image 94
julx Avatar answered Oct 08 '22 11:10

julx