Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In groovy, is there a way to check if an object has a given method?

Tags:

groovy

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?

like image 663
Electrons_Ahoy Avatar asked Oct 07 '09 21:10

Electrons_Ahoy


People also ask

Is method in Groovy?

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.

How do you call a method in Groovy?

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.

How do I know the type of a variable in 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.

How do you define 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.


1 Answers

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 } 
like image 105
Dónal Avatar answered Oct 19 '22 13:10

Dónal