我试图改变我的groovy脚本的实现方式 . 我仍然希望它们从命令行运行,但我真的想允许在同一个脚本中调用不同的方法(将它们分组),我也喜欢自动文档系统 .

我试图让这样的脚本运行:

@Doc("This is a test script")
public testScript(
    @Doc("Param 1 is optional") String param1="nobody"
)
{
    println "hello "+param1
}

如果这个被命名,说“脚本”我可以通过命令行说“脚本testScript”或“脚本testScript world”来运行该方法 . 如果您使用“script --help”,您将使用@Doc注释在屏幕上显示Usage .

我希望使用的技巧是Groovy能够为脚本指定基类 . 如果我使用-b Base我可以在执行子程序的“run”方法之前运行Base的构造函数 .

在这一点上,我需要拦截即将进入“运行”的调用,我无法弄清楚如何做到这一点 . 无论我尝试使用expandoMetaClass,invokeMethod,它们都不会拦截对子进程的run()方法的调用 . (我相信invokeMethod有一些方法可以做“继承”,但它需要一个在main()中运行的设置..而脚本没有其中之一) .

如果我承诺使用批处理文件或其他类来启动脚本,这将是微不足道的但我真的不想在命令行中添加任何东西(我希望将-b Base放在环境变量中,所以脚本仍然会像你期望的那样运行cli) .

这是我的基类的一个例子......

abstract class Base extends Script implements GroovyInterceptable {
    public Base() {
        println "This is executed"
        assert(this.class.name == "script") // it is an instance of the child script
        def metaClass = this.class.getMetaClass() // should be script's meta
        metaClass.run = this.&myRun // I believe this is supposed to work
    }
    def myRun()
    {
        println "Never called, but the script is run after Base() returns"
    }
}