groovy 실행 파일을 호출하는 방법은 Groovy 스크립트를 자바 클래스로 Java 런타임에 직접 임베드하고 호출하는 것이 효율적인 반면에 Groovy 실행 파일을 호출하는 방법은 두 번째 Java 런타임 인스턴스와 클래스 로더를 호출합니다.
1) 간단한 방법은 GroovyShell을 사용한다 : 여기서
예로 들어 자바 메인 프로그램으로 호출 그루비 스크립트 타겟팅 :
여기 자바에서 그루비 스크립트를 실행하기위한 세 가지 방법 == TestShell.java의 ==
import groovy.lang.Binding;
import groovy.lang.GroovyShell;
// call groovy expressions from Java code
Binding binding = new Binding();
binding.setVariable("input", "world");
GroovyShell shell = new GroovyShell(binding);
Object retVal = shell.evaluate(new File("hello.groovy"));
// prints "hello world"
System.out.println("x=" + binding.getVariable("x")); // 123
System.out.println("return=" + retVal); // okay
== hello.groovy의 ==
01,235,
2) 다음으로 GroovyClassLoader을 사용하여 스크립트를 클래스로 구문 분석 한 다음 해당 스크립트의 인스턴스를 만듭니다. 이 접근법은 Groovy 스크립트를 클래스로 취급하고 모든 Java 클래스에서와 마찬가지로 메소드를 호출합니다.
GroovyClassLoader gcl = new GroovyClassLoader();
Class clazz = gcl.parseClass(new File("hello.groovy");
Object aScript = clazz.newInstance();
// probably cast the object to an interface and invoke methods on it
3) 마지막으로, 당신은 GroovyScriptEngine를 만들고 변수 바인딩을 사용하여 물체에 전달할 수 있습니다. Groovy 스크립트를 스크립트로 실행하고 인수가있는 명시 적 메소드를 호출하는 대신 바인딩 변수를 사용하여 입력을 전달합니다.
참고 :이 세 번째 옵션은 그루비 스크립트를 서버에 임베드하고 수정시 다시로드하려는 개발자를위한 것입니다.
import groovy.lang.Binding;
import groovy.util.GroovyScriptEngine;
String[] roots = new String[] { "/my/groovy/script/path" };
GroovyScriptEngine gse = new GroovyScriptEngine(roots);
Binding binding = new Binding();
binding.setVariable("input", "world");
gse.run("hello.groovy", binding);
System.out.println(binding.getVariable("output"));
참고 : 이러한 접근 방식이 작동하려면 CLASSPATH에 groovy_all jar를 포함시켜야합니다.
참조 : http://groovy.codehaus.org/Embedding+Groovy
경로 환경 변수에 Groovy를 추가 했습니까? – BlackHatSamurai
[직접 실행] (http://groovy.codehaus.org/Embedding+Groovy); 그게 할 일이야 ... –
@ 블레인, 그래, 나는 그것을 확인했다. –