How to load java script having class, in jvm using nashorn

Here is my simple java script test.js with class :

class Car {
  constructor(name, year) {
    this.name = name;
    this.year = year;
  }
}

myCar = new Car("Ford", 2014);

Print("done")

Here is my java code which will try to load test.js

public class Controller {

    public static void main(String[] args) {

        try {
        
        NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
        ScriptEngine engine = factory.getScriptEngine("--language=es6");

        engine.eval(Files.newBufferedReader(Paths.get("<Path-to-test-js>/test.js"), StandardCharsets.UTF_8));
        } catch (Exception _e){
            System.out.println(_e);
        }
    }

but its throwing exception :

javax.script.ScriptException: <eval>:1:0 Expected an operand but found class
class Car {
^ in <eval> at line number 1 at column number 0

Why its throwing exception here.

Answer

I am not able to run nashorn with my scripts , i think class is not supported. If anyone is planning to use nashorn do not use it :

  • I removed class from my scripts and i tested its performance , its very slow. not even to close to expected performace of my application.
  • Even for study purpose i will not recommend it as its getting absolute. Nashorn, the JavaScript engine in the OpenJDK, has been deprecated in JDK 11 by JEP 335 and has recently been scheduled to be removed in a future JDK version by JEP 372.

Leave a Reply

Your email address will not be published. Required fields are marked *