简体   繁体   English

尝试从 Groovy 中的 class 内部调用 function,得到 MissingMethodException

[英]Trying to call a function from inside the class in Groovy, getting MissingMethodException

I'm running the following code (in Jenkins script console):我正在运行以下代码(在 Jenkins 脚本控制台中):

def sayHello() {
    println "Hello"
}

class MyClass {
    MyClass() { 
        sayHello()
    }
}

def a = new MyClass()

In all the good faith, I expect the constructor code to call the function that will print Hello .真诚地,我希望构造函数代码调用将打印Hello的 function。

Instead I get相反,我得到

groovy.lang.MissingMethodException: No signature of method: MyClass.sayHello() is applicable for argument types: () values: []
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:58)

What is going on here?这里发生了什么? I can't call the function from inside the class?我不能从 class 内部呼叫 function 吗?

You get the error because you cannot access methods of one class from another class, unless you access an instance of that class. In your case, the code is embedded automatically into a run() method inside the Main class derived from groovy.lang.Script.您收到错误是因为您无法从另一个 class 访问一个 class 的方法,除非您访问该 class 的实例。在您的情况下,代码自动嵌入到从 groovy.lang 派生的 Main class 内的 run() 方法中。脚本。 The class MyClass is an inner class of the Main class. See here Scripts versus classes . class MyClass 是 Main class 的内部 class。请参阅此处的 脚本与类

Solution: to access the method sayHello() of the Main class, you must pass an instance of it, using this keyword:解决方案:要访问 Main class 的方法 sayHello(),您必须传递它的实例,使用this关键字:

def sayHello() {
    println "Hello"
}

class MyClass {
    MyClass(Script host) {
        host.sayHello()
    }
}

def a = new MyClass(this)

Not sure what and why you are trying to do, but the simplest option to call a "function" from a constructor inside a Script is to put it in another class:不确定您要做什么以及为什么要尝试这样做,但是从脚本中的构造函数调用“函数”的最简单选择是将其放在另一个 class 中:

class A {
  static sayHello() {
    println "Hello"
  }
}

class MyClass {
    MyClass() {
        A.sayHello()
    }
}

def a = new MyClass()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM