Scripting Scripting within Java

황제낙엽 2012.01.03 14:38 조회 수 : 69

sitelink1 https://wikis.oracle.com/display/code/Scripting+within+Java 
sitelink2  
sitelink3 http://1 
sitelink4 http://ko 
sitelink5  
sitelink6 http://sitelink1 

The following code sample is from How Java Plays With Scripting Languages

 

The Java Scripting Framework provides a set of scripting APIs, which allow Java Scripting Engines to be used in Java applications. The API is intended for use by application programmers who wish to execute programs written in scripting languages, in their Java applications. Let's go through a code sample to see how this can be achieved.

 

The simplest way to use the scripting API is as follows:

 

1. Create a ScriptEngineManager object.
2. Get a ScriptEngine object from the manager.
3. Evaluate the script using the ScriptEngine's eval methods.

import javax.script.*;
public class EvalScript {
    public static void main(String[] args) throws Exception {
        // create a script engine manager
        ScriptEngineManager factory = new ScriptEngineManager();
        // create a JavaScript engine
        ScriptEngine engine = factory.getEngineByName("JavaScript");

        // create a Java object
        String name = "Tom";

        // create the binding
        engine.put("greetingname", name);

        // evaluate JavaScript code from String
        engine.eval("println('Hello, ' + greetingname)");
        engine.eval("println('The name length is ' +  greetingname.length)");
    }
}

 

The output is:

Hello, Tom
The name length is 3

 

Let's go through the code sample:

 

1. The Script Engine Discovery Mechanism identifies the Script Engine by the script name "JavaScript".
2. Create the bindings with key/value pairs, the key is "greetingname" JavaScript variable name, the value is the Java object proxy, which wraps the Java String "name".
3. The "eval()" method of Script Engine parses the JavaScript code and executes it by internally using a front-end compiler and back-end executor.
4. During the execution, the method and attribute of the Java object can be accessed from the script.