Java scriptengine: use values on the Java side?
In the Java program, I am calling a user-defined JavaScript program:
File userJSFile=...; javax.script.ScriptEngineManager mgr=new ScriptEngineManager(); javax.script.ScriptEngine scripEngine= mgr.getEngineByExtension("js"); Object result=scripEngine.eval(new java.io.FileReader(userJSFile));
Now I want to use 'result': how can I access it? Can I recognize it as an array (I can iteratively throw away its members), a string, an integer, and so on?
thank you
Editor: all I know is that my user gave me a script that returns the last value I know nothing about this value It is a string, an array, etc? I don't know, but I want to use it
Solution
In addition to simple values, I'd rather have the script engine cast its values to Java types
public class ScriptDemo { static class Result { private String[] words; public void setWords(String[] words) { this.words = words; } } static final String SCRIPT = "var foo = 'Hello World!';\n" + "result.setWords(foo.split(' '));"; public static void main(String[] args) throws ScriptException { Result result = new Result(); javax.script.ScriptEngineManager mgr = new ScriptEngineManager(); javax.script.ScriptEngine scripEngine = mgr .getEngineByExtension("js"); scripEngine.getContext().setAttribute("result",result,ScriptContext.ENGINE_SCOPE); scripEngine.eval(SCRIPT); System.out.println(Arrays.toString(result.words)); } }
Even if you cannot edit the script, you can get the return value and pass it to your own generated script to perform the enforcement operation This assumes that you know the returned value
Edit: because I know nothing about the return value, I first use Java (getclass()) to test whether it is Java One of the Lang types If the returned object comes from the private API of the library, I will introspect it using the scripting language (JavaScript in this case), and may cast it to Java type or push its properties to some java data structures in the process
My JavaScript is unfamiliar, but John Leach's tutorial looks good: Javascript introduction
(you may be able to use java reflection, but since the engine implementation may vary depending on the Java version / JRE / JavaScript engine, I won't rely on it.)