Manish Jindal
Manish Jindal

Reputation: 405

Error Caught: groovy.lang.GroovyRuntimeException: This script or class could not be run

Recently encountered with this problem- when i had two class in one groovy class if main method class is not on the top i encountered this problem.

  class Book {

    private String name 
    void setName(String bookName) {
        name=bookName
        print "Book Name => "+bookName+"\n";
    }

    String getName(){
        return name;
    }
}


class TestClass {
    static  main(args) {
        Book t = new Book();
        t.setName("First Book");
        print "book title=>"+t.getName()+"\n"
    }
}

But if change the order of these two class than there is no error, does it mean main method class should be on top in Groovy ?

Upvotes: 2

Views: 3948

Answers (1)

Sandeep Poonia
Sandeep Poonia

Reputation: 2188

Yes, order of classes matter in a groovy script. If you parse a groovy script and check its class name, it would the top level class and not the one with main method or one that have same name as the name of the file. It could be a concrete class, an abstract class, an enum, an interface or trait.

Lets see your case. We are going to put your code inside a GString and then will try to parse it using our own GroovyClassLoader.

String script = """
class Book {
    private String name 
    void setName(String bookName) {
        name=bookName
        print "Book Name => "+bookName+"\\n";
    }

    String getName(){
        return name;
    }
}


class TestClass {
    static  main(args) {
        Book t = new Book();
        t.setName("First Book");
        print "book title=>"+t.getName()+"\\n"
    }
}
"""

GroovyClassLoader loader = new GroovyClassLoader()
GroovyCodeSource codeSource = new GroovyCodeSource(script, "MyClass", GroovyShell.DEFAULT_CODE_BASE)
println loader.parseClass(codeSource)

When you will execute this code it will print class Book. Because this is the first available class in your script.

The exception you are getting is because that your top level class doesn't have a main method and neither your script have something to execute after you have loaded your classes. One solution is to move TestClass at top or just add another line at the end of the file TestClass.main() and it will execute without any issues.

Upvotes: 2

Related Questions