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

后端 未结 3 820
梦谈多话
梦谈多话 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:53

    Try the following

     public static void main(String [] args) throws Exception {
            ScriptEngine engine = new ScriptEngineManager().getEngineByName ("rhino"); 
            data data = new data();
            Context.enter().getWrapFactory().setJavaPrimitiveWrap(false);
    
            try 
            { 
                    engine.eval("function test(data) { return data.get('value1') + 5;};"); 
                    System.out.println("Result:" + ((Invocable)engine).invokeFunction("test", data)); 
            } 
            catch (Exception e) 
            { 
                    e.printStackTrace(); 
            } 
        }
    
        public static class data 
        { 
           Double value = 1.0d; 
           public Number get(String arg)  {  return value; } 
        } 
    

    Alternatively, you could modify the javascript function to explicitly cast the value to a number:

    function test(data) { return parseInt(data.get('value1'), 10) + 5;}
    

提交回复
热议问题