文章目录
一、报错信息
定义 Groovy 函数 ,
void fun(object) {
object.hello()
}
如果传入的 实例对象 中 , 没有定义 hello 方法 , 会导致如下报错 ;
报错代码 :
class Student {
def hello(){
println "Hello Student"
}
}
class Worker {
def hello(){
println "Hello Worker"
}
}
class Farmer {}
void fun(object) {
object.hello()
}
fun(new Student())
fun(new Worker())
// 下面的用法会报
// Caught: groovy.lang.MissingMethodException 异常
fun(new Farmer())
报错信息 :
Caught: groovy.lang.MissingMethodException: No signature of method: Farmer.hello() is applicable for argument types: () values: []
Possible solutions: sleep(long), sleep(long, groovy.lang.Closure), getAt(java.lang.String), each(groovy.lang.Closure), split(groovy.lang.Closure), wait()
groovy.lang.MissingMethodException: No signature of method: Farmer.hello() is applicable for argument types: () values: []
Possible solutions: sleep(long), sleep(long, groovy.lang.Closure), getAt(java.lang.String), each(groovy.lang.Closure), split(groovy.lang.Closure), wait()
at Worker$hello.call(Unknown Source)
at Groovy.fun(Groovy.groovy:20)
at Groovy$fun.callCurrent(Unknown Source)
at Groovy.run(Groovy.groovy:28)
二、解决方案
可以使用 respondsTo 方法 , 判定对象中是否定义了 hello 函数 ;
void fun(object) {
if (object.respondsTo("hello")) {
object.hello()
}
}
也可参考 【Groovy】Groovy 动态语言特性 ( Groovy 中函数实参自动类型推断 | 函数动态参数注意事项 ) 博客 , 以牺牲动态特性 , 将其限制为静态语言 , 则不会出现上述运行时错误 ;
完整代码如下 :
class Student {
def hello(){
println "Hello Student"
}
}
class Worker {
def hello(){
println "Hello Worker"
}
}
class Farmer {}
void fun(object) {
if (object.respondsTo("hello")) {
object.hello()
}
}
fun(new Student())
fun(new Worker())
// 下面的用法会报
// Caught: groovy.lang.MissingMethodException 异常
fun(new Farmer())
执行结果 :
Hello Student
Hello Worker