Use Javascript in Java 6

Here is a simple example from dev2dev website:

import java.io.FileNotFoundException;
import java.io.FileReader;

import javax.script.Bindings;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class SimpleScript {

public static void main(String[] args) throws ScriptException,

FileNotFoundException, NoSuchMethodException {

ScriptEngineManager manager = new ScriptEngineManager();

ScriptEngine engine = manager.getEngineByName("js");

// output value of vairable

engine.put("name", "hello, adam");

engine.eval("println(name)");

// evaluate a statement

engine.put("age", 15);

engine.eval("if (age > 18) {" + "println(‘you can vote!’)" + "} else {"

+ "println(‘you should be in school!’)" + "}");

// read script from file

engine.put("age", 20);

engine.eval(new FileReader("/home/adam/workspace/script/bin/test.js"));

// return a value from script

// if you are thirty years old and gendar is true, result is "Me",

// otherwise

// return value "Not me"

engine.put("age", 31);

engine.put("gendar", Boolean.TRUE);

Object result = engine.eval(new FileReader(

"/home/adam/workspace/script/bin/me.js"));

System.out.println(result);

// exchange information in Java and Javascript via bindings

Bindings bindings = engine.createBindings();

bindings.put("color", "null");

engine.eval("color = ‘red’;", bindings);

String color = (String) bindings.get("color");

System.out.println(color);

// call a java class’s method in js script

engine.eval("name2 = name.toUpperCase();" + "println(name2);");

// create a java class instance

engine.eval("importPackage(java.util);" + "today = new Date();"

+ "println(‘Today is: ‘+ today);");

// compiled script

Compilable compilable = (Compilable) engine;

CompiledScript script = compilable.compile("println(‘hello, world!’)");

script.eval();

// java call method in js script

engine.eval("function increment(i) { return i + 1; };");

Invocable invocable = (Invocable) engine;

Object i = invocable.invokeFunction("increment", new Object[] { 100 });

System.out.println(i);

}
}

Content of file me.js :

if (age > 30 && gendar == true) {
result = ‘Me’;
} else {
result = ‘Not me’;
}

Content of file test.js:

if (age > 18) {
println(‘you can vote!’);
} else {
println(‘you should be in school!’);
}

Comments are closed.