Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiled Nashorn output as Java class

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?

like image 702
R Jos Avatar asked Oct 29 '22 23:10

R Jos


1 Answers

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.

like image 178
A. Sundararajan Avatar answered Nov 09 '22 07:11

A. Sundararajan