Searching...
Thursday, 27 September 2012

Scripting in Java Example

20:27

Scripting in Java Example
Package javax.script 

Javax.script api provides the classes and interfaces for creating java script engines and executing java script inside java applications'

Example
Steps
· Instantiating Script engine manager instance with default constructor
· Creating script engine instance from Script engine manager
· Creating script context instance and add some values
· Execute Java Script
· Get the attribute values
· Print values



import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class ScriptingExample {
    public static void main(String[] args) {

        // Instantiating Script engine manager instance with default constructor
        ScriptEngineManager sem = new ScriptEngineManager();

        // Creating script engine instance from Script engine manager
        ScriptEngine engine = sem.getEngineByName("JavaScript");

        // Creating script context instance and add some values
        ScriptContext context = engine.getContext();

        context.setAttribute("a", 100, ScriptContext.ENGINE_SCOPE);
        context.setAttribute("b", 200, ScriptContext.ENGINE_SCOPE);

        // Execute Java Script
        try {
            engine.eval("print('Hello World!'); ");

            engine.eval("var total=a+b; ");

        } catch (ScriptException ex) {
            System.err.println(ex);
        }

        // Get the attribute values
        Double ans = (Double) context.getAttribute("total");
        // Print values
        System.out.println("Total value from script: " + ans);
    }
}

Output

Hello World!Total value from script: 300.0
 

References

0 comments: