GroovyでScript実行時に複数のクラスがあるとエラー発生

ソース

import static spark.Spark.*
import groovy.json.JsonBuilder

class A {
    def a = "test"
    def b = ['a':1, 'b': [111, 222, 333]]
}

class B {
    public static void main(String[] args) {

        Object.metaClass.asJson = {
            def builder = new JsonBuilder(delegate);
            builder.toString()
        }

        def obj = new A()
        get('/obj', { req, res -> obj.asJson() })
    }
}
  • Script実行すると、以下のようなエラーが出ます。
C:\hogehoge>groovy -classpath "%CLASSPATH%" src\main\groovy\foo.groovy
Caught: groovy.lang.GroovyRuntimeException: This script or class could not be run.
It should either:
- have a main method,
- be a JUnit test or extend GroovyTestCase,
- implement the Runnable interface,
- or be compatible with a registered script runner. Known runners:
  * <none>
groovy.lang.GroovyRuntimeException: This script or class could not be run.
It should either:
- have a main method,
- be a JUnit test or extend GroovyTestCase,
- implement the Runnable interface,
- or be compatible with a registered script runner. Known runners:
  * <none>

修正

  • どうやら最初のクラスにmainが無いといけないようです。

The Groovy programming language - Mailing-lists

  • ソース修正
import static spark.Spark.*
import groovy.json.JsonBuilder

class B {
    public static void main(String[] args) {

        Object.metaClass.asJson = {
            def builder = new JsonBuilder(delegate);
            builder.toString()
        }

        def obj = new A()
        get('/obj', { req, res -> obj.asJson() })
    }
}

class A {
    def a = "test"
    def b = ['a':1, 'b': [111, 222, 333]]
}

これで動いた!