Is it possible to convert Nashorn evaluated output of a Javascript into a Java Class file to be invoked later ? (like JSP --> Java--> Class file)
I have a Javascript file that is used by Nashorn to generate HTML output. The javascript file has different functions per components to generate the HTML output for each of them. These component functions are invoked dynamically through a "renderServer" function that takes component name and JSON data for that component.
private ScriptEngine nashorn;
ScriptEngineManager scriptEngineManager = new ScriptEngineManager(null);
this.nashorn = scriptEngineManager.getEngineByName("nashorn");
this.nashorn.eval(new FileReader(jsFile);
String compName="myComponent1";// Component 1 name
String jsonData="{....}";// JSON data input for myComponent
String formatted = "JSON.parse('" + jsonData + "')";
String htmlRender = "renderServer(\"" + myComponent1 + "\"," + formatted + ");";
Object finalResult = nashorn.eval(htmlRender);
I want to generate the compiled output of the evaluation and invoke the java class like instead of doing nashorn.eval every time by passing the component name and input json. Is it possible to achieve it?
No. There is no way to persist bytecode generated by nashorn and use it like a normal Java class. There is an undocumented/unsupported "--persistent-code-cache" to enable disk cache of compiled scripts - but that is still used internally by Nashorn. You can't load those classes by arbitrary class loader and call methods on it from your java code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With