Assuming that I have an object someObj
of indeterminate type, I'd like to do something like:
def value = someObj.someMethod()
Where there's no guarantee that 'someObj' implements the someMethod()
method, and if it doesn't, just return null
.
Is there anything like that in Groovy, or do I need to wrap that in an if-statement with an instanceof
check?
A method is in Groovy is defined with a return type or with the def keyword. Methods can receive any number of arguments. It's not necessary that the types are explicitly defined when defining the arguments. Modifiers such as public, private and protected can be added.
In Groovy, we can add a method named call to a class and then invoke the method without using the name call . We would simply just type the parentheses and optional arguments on an object instance. Groovy calls this the call operator: () . This can be especially useful in for example a DSL written with Groovy.
You can use the getClass() method to determine the class of an object. Also, if you want to check if an object implements an Interface or Class, you can use the instanceof keyword. That's it about checking the datatype of an object in Groovy.
A Groovy class is a collection of data and the methods that operate on that data. Together, the data and methods of a class are used to represent some real world object from the problem domain. A class in Groovy declares the state (data) and the behavior of objects defined by that class.
Use respondsTo
class Foo { String prop def bar() { "bar" } def bar(String name) { "bar $name" } } def f = new Foo() // Does f have a no-arg bar method if (f.metaClass.respondsTo(f, "bar")) { // do stuff } // Does f have a bar method that takes a String param if (f.metaClass.respondsTo(f, "bar", String)) { // do stuff }
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