Rhino (JavaScript Engine) - Example

Example

Below is an example of Java code running JavaScript print('Hello, world!')

import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; public class RhinoEngine { public static void main(String args) { ScriptEngineManager mgr = new ScriptEngineManager; // Now we can go and get a script engine we want. // This can be done either by finding a factory that supports // our required scripting language // (engine = factory.getScriptEngine;) // or by requesting a script engine that supports a // given language by name from the script engine manager. ScriptEngine engine = mgr.getEngineByName("JavaScript"); // Now we have a script engine instance that // can execute some JavaScript try { engine.put("name", args); engine.eval("print('Hello ' + name + '!')"); } catch (ScriptException ex) { ex.printStackTrace; } } }

Here is a simple example showing a Rhino script that outputs each line in the stdin converted to uppercase.

// Equivalent in effect to the Java declaration import java.io.*; importPackage(java.io); importPackage(java.lang); // "in" is a keyword in JavaScript. // In JavaScript you could query for an attribute using syntax: var reader = new BufferedReader( new InputStreamReader(System) ); // We use JavaScript's dynamic typing here to let s be a boolean first, and later on a string... var s = true; while (s) { s = reader.readLine; if (s) { System.out.println(s.toUpperCase); } }

Read more about this topic:  Rhino (JavaScript Engine)

Famous quotes containing the word example:

    Our intellect is not the most subtle, the most powerful, the most appropriate, instrument for revealing the truth. It is life that, little by little, example by example, permits us to see that what is most important to our heart, or to our mind, is learned not by reasoning but through other agencies. Then it is that the intellect, observing their superiority, abdicates its control to them upon reasoned grounds and agrees to become their collaborator and lackey.
    Marcel Proust (1871–1922)