【错误记录】Groovy 函数参数动态类型报错 ( Caught: groovy.lang.MissingMethodException: No signature of method )
生活随笔
收集整理的這篇文章主要介紹了
【错误记录】Groovy 函数参数动态类型报错 ( Caught: groovy.lang.MissingMethodException: No signature of method )
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
文章目錄
- 一、報(bào)錯(cuò)信息
- 二、解決方案
一、報(bào)錯(cuò)信息
定義 Groovy 函數(shù) ,
void fun(object) {object.hello() }如果傳入的 實(shí)例對(duì)象 中 , 沒(méi)有定義 hello 方法 , 會(huì)導(dǎo)致如下報(bào)錯(cuò) ;
報(bào)錯(cuò)代碼 :
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())// 下面的用法會(huì)報(bào) // Caught: groovy.lang.MissingMethodException 異常 fun(new Farmer())報(bào)錯(cuò)信息 :
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 方法 , 判定對(duì)象中是否定義了 hello 函數(shù) ;
void fun(object) {if (object.respondsTo("hello")) {object.hello()} }也可參考 【Groovy】Groovy 動(dòng)態(tài)語(yǔ)言特性 ( Groovy 中函數(shù)實(shí)參自動(dòng)類(lèi)型推斷 | 函數(shù)動(dòng)態(tài)參數(shù)注意事項(xiàng) ) 博客 , 以犧牲動(dòng)態(tài)特性 , 將其限制為靜態(tài)語(yǔ)言 , 則不會(huì)出現(xiàn)上述運(yùn)行時(shí)錯(cuò)誤 ;
完整代碼如下 :
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())// 下面的用法會(huì)報(bào) // Caught: groovy.lang.MissingMethodException 異常 fun(new Farmer())執(zhí)行結(jié)果 :
Hello Student Hello Worker總結(jié)
以上是生活随笔為你收集整理的【错误记录】Groovy 函数参数动态类型报错 ( Caught: groovy.lang.MissingMethodException: No signature of method )的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 【Groovy】Groovy 动态语言特
- 下一篇: 【Groovy】Groovy 动态语言特