제가 알고 있듯이 Java로 Groovy 스크립트를 컴파일하는 방법은 최소한 두 가지가 있습니다.컴파일 된 Groovy 스크립트
CompiledScript으로 변환하려면 javax.script.ScriptEngine을 사용하십시오.
ScriptEngine engine = new ScriptEngineManager().getEngineByName("Groovy"); Bindings bindings = new SimpleBindings(); bindings.put("foo", 1234); Compilable compEngine = (Compilable)engine; CompiledScript cs = compEngine.compile("if (foo == 1234) true else false"); cs.eval(bindings);
사용
GroovyClassLoader#parse
, 일부 중간 일을하고GroovyObject#invokeMethod(String, Object[])
를 호출합니다.
주 - 다음 코드는 Groovy in Action입니다. Groovy를 배우기에 훌륭한 책이라는 것을 알게되었습니다. 값으로 변수 이름 - 나는이 두 방식의 차이점을 알고있는 것처럼
GroovyClassLoader gcl = new GroovyClassLoader();
// Note, assume that the Groovy script gets compiled to a class that
// includes a method, "do". And "do" accepts an `Integer` argument, "foo."
Class foo = gcl.parseClass("if (foo == 1234) true else false");
GroovyObject hello = (GroovyObject) foo.newInstance();
Object[] args = { Integer.valueOf(1234) };
assert true == (foo.invokeMethod("do", args));
은, 첫 번째는 key-value
쌍와 Bindings
지도를 채우는 포함한다. 그런 다음 Bindings
인수가 변형 된 CompiledScript#eval(Bindings)
을 통해 CompiledScript
을 실행합니다.
그러나 Foo
클래스 개체를 메서드 Foo#do
에 전달하려고한다고 가정 해 보겠습니다. 그리고 if (foo == 1234) ...
을 평가하기보다는 소스 코드에서 다음과 같이 작성해야합니다.
if(fooObj.getFoo() == 1234) ...
.
그러면 결과적으로 후 처리 올바른 방법을 포함하여 foo
에 도착해야합니다.
일반적으로 위의 예에 따라 두 번째 방법을 구현하는 간단한 방법이 있습니까?
기본적으로 Java에서 Groovy 스크립트를 호출합니다.'CompiledScript'에 대해 제가 좋아하는 것은 제가 쉽게 재사용 할 수 있다는 것입니다. 'Class' 접근 방식으로, 실제 Groovy DSL 스크립트를 올바른 클래스로 수정해야합니다. 그러나'CompiledScript' 접근법을 사용하면 Groovy DSL을 그대로 유지할 수 있습니다. 그런 다음'CompiledScript # eval (Bindings) '을 호출하여 평가할 수 있습니다. –
'Script' 클래스에는 이미'Binding' 인스턴스가 포함되어 있으므로 아무것도하지 않아도됩니다. 새 인스턴스를 만들지 않으면 스레드로부터 안전하지 않습니다. – melix
만약'Bindings'의'당신이 새로운 인스턴스를 만들지 않는다면, 당신은 thread safe가 아닙니다 -'? –