gpt4 book ai didi

javascript - Rhino 将 java.lang.String 转换为 JavaScript 字符串

转载 作者:行者123 更新时间:2023-12-03 09:32:49 31 4
gpt4 key购买 nike

Context.javaToJS 似乎只是直接传递 java.lang.Strings 。

我正在对 JavaScript 进行沙箱处理(根据 http://codeutopia.net/blog/2009/01/02/sandboxing-rhino-in-java/ ),因此 java.lang.String 在 JavaScript 中不可用,除非我在 ClassShutter 中打洞(我宁愿不做)。

我是否遗漏了一些明显的东西?

最佳答案

试试这个:

ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");
ScriptContext context = engine.getContext();
context.setAttribute("jsString", "I am Java String", ScriptContext.ENGINE_SCOPE);
context.setAttribute("jsBoolean", true, ScriptContext.ENGINE_SCOPE);
context.setAttribute("jsNumber", 123456, ScriptContext.ENGINE_SCOPE);
engine.eval("function getValueAndType(obj){return obj + ' - ' + typeof obj;}");
Assert.assertEquals("Something wen wrong", "I am Java String - string", engine.eval("getValueAndType(jsString)"));
Assert.assertEquals("Something wen wrong", "true - boolean", engine.eval("getValueAndType(jsBoolean)"));
Assert.assertEquals("Something wen wrong", "123456 - number", engine.eval("getValueAndType(jsNumber)"));

关于javascript - Rhino 将 java.lang.String 转换为 JavaScript 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31448011/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com