tags:

views:

105

answers:

4

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?

+2  A: 

You should be able to do something like:

SomeObj.metaClass.getMetaMethod("someMethod")

Or you can fall back to the good old Java reflection API.

Langali
+2  A: 

Just implement method missing in you class:

class Foo {
   def methodMissing(String name, args) { return null; }
}

And then, every method time you try to invoke a method that don't exists, you will get a null value.

def foo = new Foo();
assert foo.someMethod(), null

For more information, take a lot here: http://groovy.codehaus.org/Using+methodMissing+and+propertyMissing

HTH

marcospereira
That means all his Objects that don't have the someMethod behavior would have to implement the method?
Langali
+3  A: 

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
}
Don
A late in responding, but this was exactly what I was looking for. Thanks!
Electrons_Ahoy
+1  A: 

You can achieve this by using getMetaMethod together with the safe navigation operator ?.:

def str = "foo"
def num = 42

def methodName = "length"
def args = [] as Object[]

assert 3 == str.metaClass.getMetaMethod(methodName, args)?.invoke(str, args);
assert null == num.metaClass.getMetaMethod(methodName, args)?.invoke(num, args);
Christoph Metzendorf