import java.io.*; import javax.script.*; public class Jtest{ public static void main(String[] args){ ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine js = factory.getEngineByName("JavaScript"); Bindings b = new SimpleBindings(); try { js.eval("function f(){}",b); js.eval(""); } catch (ScriptException e){ System.out.println(e); } System.out.printf("visible names: %s\n",b.entrySet()); // Bindings b contains here the list of the (predefined) names that are visible when // a new one is defined using eval(). This allows this a program, when it defines // a new function to test in advance that it does not redefine a predefined one, which // can easily be done getting the functions of Bindings b and saving them in a table, // and then testing that the new function name being defined is not one of them. Class funClass; funClass = (Class)b.get("print").getClass(); System.out.printf("function %s\n",funClass); // build here a table of predefined functions // suppose here the program wants to define a new function "print", but does not // want to redefine a predefined one. It tests if the name "print" is a function. Object obj = js.get("print"); if (obj.getClass() == funClass){ System.out.printf("print is a function\n"); // check that it is not a predefined one by testing if this object is in // the table of predefined functions } } /* output rhino: visible names: [f=sun.org.mozilla.javascript.internal.InterpretedFunction@1eef0a8, context=javax.script.SimpleScriptContext@1f9e529, print=sun.org.mozilla.javascript.internal.InterpretedFunction@133e8c9, println=sun.org.mozilla.javascript.internal.InterpretedFunction@f7e9dd] function class sun.org.mozilla.javascript.internal.InterpretedFunction print is a function output nashorn: visible names: [nashorn.global=[object global]] Exception in thread "main" java.lang.NullPointerException at Jtest.main(Jtest.java:25) */ }