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) }
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'.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With