假设我有一个someObj不确定类型的对象,我想做类似的事情:
def value = someObj.someMethod()
Run Code Online (Sandbox Code Playgroud)
如果不能保证'someObj'实现该someMethod()方法,如果没有,则返回null.
在Groovy中是否有类似的东西,或者我需要将其包含在带有instanceof支票的if语句中?
Dón*_*nal 68
使用 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
}
Run Code Online (Sandbox Code Playgroud)
只需在您的类中实现 methodMissing 即可:
class Foo {
def methodMissing(String name, args) { return null; }
}
Run Code Online (Sandbox Code Playgroud)
然后,每次尝试调用不存在的方法时,您都会得到一个空值。
def foo = new Foo();
assert foo.someMethod(), null
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请查看此处:http ://groovy.codehaus.org/Using+methodMissing+and+propertyMissing