简体   繁体   中英

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

I'm running the following code (in Jenkins script console):

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 .

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?

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. The class MyClass is an inner class of the Main class. See here Scripts versus classes .

Solution: to access the method sayHello() of the Main class, you must pass an instance of it, using this keyword:

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 A {
  static sayHello() {
    println "Hello"
  }
}

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

def a = new MyClass()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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