JDK 6 - 05: Scripting : InvokeScriptMethod


Written on 오전 2:46 by 강여사(J.Y.Kang)

만약 스크립팅 언어가 객체 기반(자바 스크립트와 같은) 혹은 객체 지향이라면, 스크립트 객체에 스크립트 메소드를 호출할 수 있다.

package test;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

public class InvokeScriptMethod {

public static void main(String[] args) throws Exception {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");

// JavaScript code in a String. This code defines a script object 'obj'
// with one method called 'hello'.
String script = "var obj = new Object(); obj.hello = function(name) { print('Hello, ' + name); }";
// evaluate script

// javax.script.Invocable is an optional interface.
// Check whether your script engine implements or not!
// Note that the JavaScript engine implements Invocable interface.
Invocable inv = (Invocable) engine;

// get script object on which we want to call the method
Object obj = engine.get("obj");

// invoke the method named "hello" on the script object "obj"
inv.invokeMethod(obj, "hello", "Script Method !!");

If you enjoyed this post Subscribe to our feed

No Comment

댓글 쓰기