Groovy脚本传递命令行参数失败,执行报错如何解决?
Hey there! Let's get this sorted out—your error comes from a tiny syntax misstep in your script, and once we fix that, your argument passing will work perfectly.
What Went Wrong
In Groovy, when you reference the closure variable it directly inside println, you don’t need to wrap it with ${}. That syntax is only for string interpolation, not for passing a variable directly to a method. Your original code was trying to call a non-existent $() method on the closure, which triggered the MissingMethodException.
Corrected Script
Here’s the fixed version of your script:
class Main { static void main(String... args) { args.each { println it } // Or use explicit parentheses if you prefer: args.each { println(it) } } }
Your Argument-Passing Command is Correct!
The Windows command you’re using is already right:
Groovy myscript.groovy "arg1" "arg2"
When you run this now, the script will loop through each argument and print them, giving you this output:
arg1 arg2
Bonus: String Interpolation Option
If you ever want to include the argument in a formatted string, that’s where ${it} makes sense. For example:
args.each { println "Received argument: ${it}" }
This would output:
Received argument: arg1 Received argument: arg2
内容的提问来源于stack exchange,提问作者Cortlendt

