【错误记录】Groovy 函数参数动态类型报错 ( Caught: groovy.lang.MissingMethodException: No signature of method )
生活随笔
收集整理的這篇文章主要介紹了
【错误记录】Groovy 函数参数动态类型报错 ( Caught: groovy.lang.MissingMethodException: No signature of method )
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 一、報錯信息
- 二、解決方案
一、報錯信息
定義 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總結
以上是生活随笔為你收集整理的【错误记录】Groovy 函数参数动态类型报错 ( Caught: groovy.lang.MissingMethodException: No signature of method )的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Groovy】Groovy 动态语言特
- 下一篇: 【Groovy】MOP 元对象协议与元编