Search code examples
groovy

Groovy program structure question around main method


I'm trying to write a Groovy program and can't figure out what I'm doing wrong.

package mypackage

class myclass {
    def myvar

    def mymethod() {
        myvar = "here"
        println "i am ${myvar}"
    }

    def static main(args) {
        mymethod()
        println "hello "
    }
}

In my example I think I am -

  1. declaring a package "mypackage"
  2. creating a class "myclass"
  3. creating a class variable "myvar"
  4. creating a class method "mymethod"
  5. creating a class method "main" expecting this to be called at invocation

So I'm expecting "main" to be called with all my command line arguments. It will call "mymethod" which will update the class variable "myvar" and then print a GString interpolating "myvar". And then control will return to "main" at which point it will print "hello".

But none of this is happening. Instead, when I attempt to execute it I get

$ groovy myclass
Caught: groovy.lang.MissingMethodException: No signature of method: static mypackage.myclass.mymethod() is applicable for argument types: () values: []
Possible solutions: mymethod()
groovy.lang.MissingMethodException: No signature of method: static mypackage.myclass.mymethod() is applicable for argument types: () values: []
Possible solutions: mymethod()
        at mypackage.myclass.main(myclass:7)

I think this is a general program structure question.


Solution

  • The main method is static and is indeed being invoked. But at this stage, you have no instance of myclass, so shouldn't expect to be able to call the instance method mymethod.

    You can either change myvar and mymethod to be static, or change the first line in main to be:

    new myclass().mymethod()