首页 > 解决方案 > 为什么groovy中会出现MissingMethodException的错误?

问题描述

class Example { 

    static Integer errorCount

    static Integer updateGlobalInteger(Integer errorC){
        errorCount=errorC
        return errorCount
    }
    static void main(String[] args) { 
        List<String> log = ["ABCD","WARNING"]
        println(log)

        def error = log.toString().replace("]","").replace("[","")
        println(error)

        def contain = error.find("ERROR") //if it is null, then error occur
        println(contain) 

        Integer errorC = contain.size()
        println(errorC)

        updateGlobalInteger(errorC)
    } 
}

有一个错误消息,

Caught: groovy.lang.MissingMethodException: No signature of method: static
Example.updateGlobalInteger() is applicable for argument types: (java.lang.Integer) values: [10]
Possible solutions: updateGlobalInteger(java.lang.Integer)
groovy.lang.MissingMethodException: No signature of method: static Example.updateGlobalInteger() is
applicable for argument types: (java.lang.Integer) values: [10]
Possible solutions: updateGlobalInteger(java.lang.Integer)
at Example.main(main.groovy:14)

我在https://www.tutorialspoint.com/execute_groovy_online.php上对其进行了测试

谢谢大家,当我尝试执行代码时,遇到以下错误。

Condition not satisfied:
updateGlobalInteger(errorC)
|                   |
0                   0

java.lang.NullPointerException: Cannot invoke method size() on null object
at org.codehaus.groovy.runtime.NullObject.invokeMethod(NullObject.java:91)

标签: groovyintreturn

解决方案


错误消息说您不能直接访问静态区域中的非静态方法,这在 java文档中明确指定

捕获:groovy.lang.MissingMethodException:没有方法签名:静态 Example.updateGlobalInteger()

类方法不能直接访问实例变量或实例方法——它们必须使用对象引用。此外,类方法不能使用 this 关键字,因为没有实例可供 this 引用。

所以要么将该方法设为静态

static Integer updateGlobalInteger(Integer errorC) {
    errorCount=errorC
   return errorCount
}

或者通过使用对象引用

static void main(String[] args) { 
 // Example of an Integer using def 
 def rint = 1..10
 Integer errorC = rint.size().toInteger()
 println(errorC) //print result is 10
 Example e = new Example()
 e.updateGlobalInteger(errorC)
} 

推荐阅读