0

有:

class Task {
    Integer code
    String name
}

def classDefinition = """
            package untitled24

            class TasksCommand {
                List tasks = [].withDefault { new Task() }
            }
            TasksCommand
        """

def shell = new GroovyShell(this.class.classLoader)
Class<?> definedClass = shell.evaluate(classDefinition)

执行结果为:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
Script1.groovy: 5: unable to resolve class Task 
 @ line 5, column 47.
   List tasks = [].withDefault { new Task()
                             ^

任何的想法?(groovy 版本是 1.8.8)

4

1 回答 1

0

那是因为你的Task定义不在包里,所以里面的代码untitled24找不到类...

如果您将以上内容更改为:

package woo

class Task {
  Integer code
  String name
}

def classDefinition = """package untitled24
                        |
                        |class TasksCommand {
                        |  List tasks = [].withDefault { new woo.Task() }
                        |}
                        |TasksCommand""".stripMargin()

def shell = new GroovyShell(this.class.classLoader)
Class<?> definedClass = shell.evaluate(classDefinition)

它应该可以工作...(stripMargin为便于阅读而添加)

于 2012-09-13T15:07:58.837 回答