当前位置:网站首页>[error record] groovy function parameter dynamic type error (guess: groovy.lang.missingmethodexception: no signature of method)

[error record] groovy function parameter dynamic type error (guess: groovy.lang.missingmethodexception: no signature of method)

2022-07-05 22:18:00 Programmer community

List of articles

  • One 、 Error message
  • Two 、 Solution

One 、 Error message


Definition Groovy function ,

void fun(object) { 
        object.hello()}

If the incoming Instance object in , No definition hello Method , This will result in the following error reports ;

Error code :

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())//  The following usage will report // Caught: groovy.lang.MissingMethodException  abnormal fun(new Farmer())

Error message :

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)

 Insert picture description here

Two 、 Solution


have access to respondsTo Method , Determine whether hello function ;

void fun(object) { 
        if (object.respondsTo("hello")) { 
            object.hello()    }}

Also can reference 【Groovy】Groovy Dynamic language features ( Groovy Automatic type inference of function arguments in | Precautions for function dynamic parameters ) Blog , At the expense of dynamic characteristics , Limit it to static languages , Then the above runtime error will not occur ;

The complete code is as follows :

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())//  The following usage will report // Caught: groovy.lang.MissingMethodException  abnormal fun(new Farmer())

Execution results :

Hello StudentHello Worker

原网站

版权声明
本文为[Programmer community]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140437187700.html