简体   繁体   English

如何使用Java命令运行Groovy脚本?

[英]How to run Groovy script with java command?

Trying to get the following script: 尝试获取以下脚本:

class MyClass {
  static void main(String... args) {
    println "Hello ${args[0]}"
  }
}

To run like Java with: java MyTest John for example. 要像Java一样运行,例如: java MyTest John

Reading the groovy docs on scripts with main I was under the impression I could to the following to achieve my goal: 通过main阅读有关脚本的常规文档,我的印象是我可以做到以下几点:

  1. Run groovyc MyTest.groovy 运行groovyc MyTest.groovy
  2. Run java MyTest John 运行java MyTest John

I was even under the impression that I could leave just the body of the main function and still be able to compile until a class that extends from Script ... 我什至有一种印象,就是我可以只留下main函数的主体,并且仍然可以编译,直到从Script扩展出一个类为止。

I can run the script with groovy MyTest.groovy John and (after compiling with groovyc ) groovy MyTest John 我可以使用groovy MyTest.groovy John和(使用groovy MyTest.groovy John编译后) groovy MyTest John运行脚本groovyc

How can I accomplish my goal? 我如何实现我的目标? What am I doing wrong? 我究竟做错了什么?

You need groovy on the classpath when you run the java command, ie: 运行java命令时,需要在类路径上使用Groovy,即:

Save this as MyClass.groovy 将此另存为MyClass.groovy

class MyClass {
  static main(args) {
    println "Hello ${args[0]}"
  }
}

Then run: 然后运行:

groovyc MyClass.groovy

Then run: 然后运行:

java -cp $GROOVY_HOME/embeddable/groovy-all-2.4.4.jar:. MyClass John

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM