Rhino [removed] How to convert Object to a Javascript primitive?

后端 未结 3 854
梦谈多话
梦谈多话 2021-01-15 15:00

I am utilizing the javax.scripting with Rhino in this project.

I have a Java method that returns a Java Object (Double, Long, Integer, etc). I want to call that

3条回答
  •  半阙折子戏
    2021-01-15 15:42

    I developed this application where you enter a set of mathematical formulas that will be evaluated by the JavaScript engine built into Java 6, which I believe is a port of rhino. The idea was that we would have a set of maps and these maps would contain variables, such as:

    MAP["VALUE 1"]
    MAP["VALUE 2"]
    

    I used that approach as some of the expressions for the formulas came from variables that were under my control and that could be invalid JS identifiers. My first approach was to declare a map and add it to the JS engine, but it failed in the same way that it's failing with you - it was interpreting it as a string, and not as a number.

    The solution was to parse the formula, figure out what variables are being used by it, and then declare the object inside the JS engine.

    Something like this:

    var MAP = new Object();
    MAP["VALUE 1"] = 1;
    MAP["VALUE 2"] = 2;
    

    And thenMAP["VALUE 1"] + MAP["VALUE 2"] will return 3, and not 12.

    There may be a better solution around, but once you go around the initial coding/ parsing, the above will always work. In our case there's a phase where we execute the "declarative" statements, and another phase where we execute the formulas. The JS engine is REALLY fast, so it's not a problem for us.

提交回复
热议问题