Printing a Message on the Standard Output Using Different Scripting Languages - Java Scripting

Java examples for Scripting:Run Script

Description

Printing a Message on the Standard Output Using Different Scripting Languages

Demo Code

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

public class Main {
  public static void main(String[] args) {
    ScriptEngineManager manager = new ScriptEngineManager();
    execute(manager, "JavaScript", "print('Hello JavaScript')");
    execute(manager, "Groovy", "println('Hello Groovy')");
    execute(manager, "jython", "print 'Hello Jython'");
    execute(manager, "jruby", "puts('Hello JRuby')");
  }//from ww w  .ja  va  2  s .  co  m

  public static void execute(ScriptEngineManager manager,
                             String engineName,
                             String script) {
    ScriptEngine engine = manager.getEngineByName(engineName);
    if (engine == null) {
      System.out.println(engineName + " is not available.");
      return;
    }
    try {
      engine.eval(script);
    }
    catch (ScriptException e) {
      e.printStackTrace();
    }
  }
}

Result


Related Tutorials