In earlier post, you have checked how a simple expression can be evaluated using ScriptEngineManager. One of the limitation in that program was expression passed to the ScriptEngine was static. So the program written here explains how we can pass dynamic values to the Engine and hence enhance the capability of the API.
Output:
Program to execute is
---------------------------------
var status='';var teamID_1 = 'AT';var teamID_2= 'HT';/*Add comments like this*/if(teamID_1==teamID_2) status='Teams are same';else status='Teams are not same';print('Inside script::: teamID_1='+teamID_1+' teamID_2='+teamID_2);;
---------------------------------
Inside script::: teamID_1=AT teamID_2=HT
status =Teams are not same
So in above program, teamID_1 & teamID_2 are the values that can be substituted at run time of the program and moreover the output from the program can be expected as String data Type.
package myjava;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class ScriptEngineTest {
/**
* @param args
* @throws ScriptException
*/
public static void main(String[] args) {
try {
String status = "";
ScriptEngineManager sem = new ScriptEngineManager();
javax.script.ScriptEngine e = sem.getEngineByName("JavaScript");
ScriptEngineFactory f = e.getFactory();
String teamID_1 = "'AT'";
String teamID_2 = "'HT'";
String script = "var status='';" +
"var teamID_1 = "+ teamID_1+";"
+ "var teamID_2= "+ teamID_2+";"
+ "/*Add comments like this*/"
+"if(teamID_1==teamID_2) status='Teams are same';"
+"else status='Teams are not same';"
+"print('Inside script::: teamID_1='+teamID_1+' teamID_2='+teamID_2);";
//System.out.println("Script\n" + script);
String program = f.getProgram(script);
System.out.println("Program to execute is ");
System.out.println("---------------------------------\n"+program);
System.out.println("\n---------------------------------");
e.eval(program);
status = (String) e.get("status");
System.out.println("\nstatus =" + status);
} catch (ScriptException e) {
e.printStackTrace();
}
}
}
Output:
Program to execute is
---------------------------------
var status='';var teamID_1 = 'AT';var teamID_2= 'HT';/*Add comments like this*/if(teamID_1==teamID_2) status='Teams are same';else status='Teams are not same';print('Inside script::: teamID_1='+teamID_1+' teamID_2='+teamID_2);;
---------------------------------
Inside script::: teamID_1=AT teamID_2=HT
status =Teams are not same
So in above program, teamID_1 & teamID_2 are the values that can be substituted at run time of the program and moreover the output from the program can be expected as String data Type.