Loading and Executing internal JavaScript from Java - Java Scripting

Java examples for Scripting:Run Script

Description

Loading and Executing internal JavaScript from Java

Demo Code

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class Main {

  public static void main(String[] args) {
    ScriptEngineManager sem = new ScriptEngineManager();
    ScriptEngine nashorn = sem.getEngineByName("nashorn");
    try {// ww  w . j a v a  2s .  c  o m
        nashorn.eval("function a(width, length, avgDepth){var volume = avgDepth * width * length;"
                + "                                             return volume * 1.8; }");
        nashorn.eval("print('Gallons of water in pool: '+ a(6,2,5))");
    } catch (ScriptException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
}

Result


Related Tutorials