Rhino Javascript:如何将Object转换为Javascript原语? [英] Rhino Javascript: How to convert Object to a Javascript primitive?
问题描述
我在这个项目中使用了带有Rhino
的javax.scripting。
I am utilizing the javax.scripting with Rhino in this project.
我有一个返回Java对象的Java方法(Double,Long,
Integer等)。我想从javascript调用该方法,
将结果作为Javascript基元类型引用。但是,
javacript将返回类型识别为Object。
I have a Java method that returns a Java Object (Double, Long, Integer, etc). I want to call that method from javascript and reference the result as a Javascript primitive type. However, javacript recognizes the return type as an Object.
如何强制它转换为javascript原语?
How do I force it to convert to a javascript primitive?
问题在于如何获取对上下文的引用以及
WrapFactory?
The problem with that is how do I get a reference to the context and the WrapFactory?
示例代码:
public class data
{
Double value = 1.0d;
public Number get() { return value; }
}
public static void main(String[] args)
{
ScriptEngine engine = new ScriptEngineManager().getEngineByName ("rhino");
data data = new data();
try
{
engine.eval("function test(data) { return data.getD('value1') + 5;};");
System.out.println("Result:" + ((Invocable)engine).invokeFunction("test", data));
}
catch (Exception e)
{
e.printStackTrace();
}
}
输出:
结果:15
Output: Result: 15
推荐答案
尝试以下
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; }
}
或者,你可以修改javascript函数以显式地将值转换为数字:
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;}
这篇关于Rhino Javascript:如何将Object转换为Javascript原语?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!