有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何捕获传递给Groovy脚本的参数?

我刚从Groovy开始。我在任何地方都找不到任何关于如何处理Groovy脚本参数的示例,所以我自己黑了这个方法。一定有更好的办法吗?如果是这样的话,我正在寻找更好的方法,因为我可能忽略了显而易见的东西

import groovy.lang.Binding;
Binding binding = new Binding();
int x = 1
for (a in this.args) {
  println("arg$x: " + a)
  binding.setProperty("arg$x", a);
  x=x+1
}
println binding.getProperty("arg1")
println binding.getProperty("arg2")
println binding.getProperty("arg3")

共 (6) 个答案

  1. # 1 楼答案

    它与Java非常相似,可以使用相同的Java语法。例如

    class TestExecutor {
    
        public static void main(def args) {
            println("Printing arguments");
            for(String arguments : args) {
                println (arguments);
            }
        }
    
    } 
    

    运行它,您应该会看到打印的参数

    C:\Users\athakur\Desktop>groovy TestExecutor.groovy test1 test2 test3
    Aug 16, 2014 11:47:56 AM org.codehaus.groovy.runtime.m12n.MetaInfExtensionModule
     newModule
    WARNING: Module [groovy-nio] - Unable to load extension class [org.codehaus.groo
    vy.runtime.NioGroovyMethods]
    Printing arguments
    test1
    test2
    test3
    

    还请注意,如果您没有提供main方法或上面示例中的方法,那么可以将参数设置为args[i],但可以更改数组的名称(同样与java相同)。所以你可以有这样的东西-

    public static void main(def argsNew) {
        println("Printing arguments");
        for(String arguments : argsNew) {
            //using args in above for loop will throw error
            println (arguments);
        }
    }
    

    重点是它不是硬编码的东西。最后,正如其他答案中所建议的,您可以始终使用CliBuilder进行智能解析。但在这方面,它也在内部使用了def options = cli.parse(args)

  2. # 2 楼答案

    如果您想要更高级的解析,而不仅仅是获取参数,那么可以使用Groovy CliBuilder来帮助您。它可以帮助您使用命令行标志、可选参数和打印使用说明

    签出CliBuilder的Javadoc或MrHakispost关于它

  3. # 3 楼答案

    如果使用--compile-static--type-checked选项运行脚本,args变量将不可见,因此编译会抛出错误:

    [Static type checking] - The variable [args] is undeclared.

    我喜欢在脚本的顶部执行以下操作:

    import groovy.transform.Field
    
    @Field String[] args = binding.getVariable('args') as String[]
    

    这将把args作为一个全局变量公开,可以在脚本中的任何地方使用


    参考文献:

    https://stackoverflow.com/a/53783178/2089675

    https://groovy-lang.org/structure.html#_variables

  4. # 4 楼答案

    试试这个:

    args.each{println it}
    
  5. # 5 楼答案

    抱歉问这个问题。我刚想出来:

    println args[0]
    println args[1]
    println args[2]
    
  6. # 6 楼答案

    最简单的方法就是使用this.args作为数组,例如:

    测试。groovy

    println this.args[0]
    

    电话:

    C:>groovy test this
    

    输出:

    this