Access Java API in Groovy Script

$ cat Hello.java

package test;

public class Hello {

public int myadd(int x, int y) {

  return 10 * x + y;

}

}

$ cat myapp.groovy

import test.Hello

def hello = new Hello()

println hello.myadd(13, 5)

$ javac Hello.java

$ mkdir test;mv Hello.class test

$ tree

.

├── groovy-all-2.2.1.jar

├── Hello.java

├── myapp.groovy

└── test

└── Hello.class

$ java -cp .:groovy-all-2.2.1.jar groovy.ui.GroovyMain myapp.groovy

135

Note:

  1. You can't use groovy-2.2.1.jar here, or you will get a NoClassDefFoundError;

  2. If your groovy script don't access other Java class, you can simply run "java -jar groovy-all-2.2.1.jar myapp.groovy".

原文地址:https://www.cnblogs.com/darkmatter/p/3605691.html