Home > Articles > Programming

  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend

Evaluate a String-Based Script

Because a script engine is represented as an instance of a class that implements interface ScriptEngine or that subclasses the AbstractScriptEngine class (which implements ScriptEngine), you can invoke any of six eval() methods to evaluate scripts. For example, you might invoke public Object eval(String script) to evaluate a string-based script. This method returns the script's result as an object—null if there is no result. An instance of the checked ScriptException class is thrown if the script has an error. Take a look at Listing 2.

Listing 2: ScriptDemo2.java

// ScriptDemo2.java

import javax.script.*;

public class ScriptDemo2
   public static void main (String [] args) throws ScriptException
      // Create a ScriptEngineManager that discovers all script engine
      // factories (and their associated script engines) that are visible to
      // the current thread's classloader.

      ScriptEngineManager manager = new ScriptEngineManager ();

      // Obtain a ScriptEngine that supports the JavaScript short name.

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

      // Evaluate a script that does not return an object.

      Object o = engine.eval ("println ('Hello, World')");
      System.out.println ("Object value: " + o);

      // Evaluate a second script that returns an object.

      o = engine.eval ("Math.cos (Math.PI)");
      System.out.println ("Object value: " + o);
      System.out.println ("Object is Double: " + (o instanceof Double));

After obtaining a ScriptEngineManager and using this object to obtain a JavaScript-based ScriptEngine, ScriptDemo2 invokes Object o = engine.eval ("println ('Hello, World')"); , which sends Hello, World to the standard output device—and also returns null. ScriptDemo2 next invokes o = engine.eval ("Math.cos (Math.PI)"); to evaluate a math expression via JavaScript's built-in Math type. The result of this expression is returned to Java in a Double object.

ScriptDemo2 creates the following output:

Hello, World
Object value: null
Object value: -1.0
Object is Double: true
  • + Share This
  • 🔖 Save To Your Account