从Java调用运行在Rhino内部的Javascript函数非常容易--这毕竟就是创建Rhino的原因。我很难确定的是:
Storage的类,它提供公共、静态、readFromFile(String fileName)、writeToFile(String fileName,String data)等方法。我不太清楚该如何做到这一点。从我到目前为止所做的搜索中,涉及到使用ScriptableObject.putProperty将所涉及的Java类传递给JavaScript,在我的例子中是Storage。然而,应该如何做到这一点,然后如何在JS端使用它,这让我感到非常困惑。
我非常感谢在座的任何人,他们可能会为我指明正确的方向。
发布于 2016-09-30 08:02:30
考虑到犀牛在这里的关注者还不到100人,这个问题没有得到回答也许就不足为奇了。同时,我自己找到了解决方案,结果非常简单。我在下面分享它,是为了让其他人都能碰到这个线程。
我的Storage类非常简单。就像这样
public class Storage
{
public static boolean haveFile(){}
public static boolean readFromFile(String fname){}
...
} 当我通过Rhino从Java调用Javascript时,我只是传递一个Storage类的新实例作为我的最后一个函数参数
Context rhino = Context.enter();
Object[] functionParams = new Object[] {"Other parameters",new Storage()};
rhino.setOptimizationLevel(-1);
try
{
Scriptable scope = rhino.initStandardObjects();
String rhinoLog = "var log = Packages.io.vec.ScriptAPI.log;";
String code = /*Javascript code here* as shown separately below/;
rhino.evaluateString(scope, rhinoLog + code, "ScriptAPI", 1, null);
Function function = (Function) scope.get("jsFunction", scope);
Object jsResult = function.call(rhino,scope,scope,functionParams);
}其中Javascript代码是
function jsFunction(a,s)
{
//a - or a,b,c etc - here will be the "other" parameters
//s - will be the instance of the Java side Storage class passed above
//now you can do things like
s.writeToFile('fileName','fileData');
var fd = s.readFromFile('fileName');
s.dropFile('fileName');
...
}https://stackoverflow.com/questions/39771148
复制相似问题