我正在寻找从 rhino 中的 javascript 覆盖 java 方法。这是我的代码:
public class CustomClass {
public String s="some string";
public void doSomething(){}
}
进而:
Object wrappedOut = Context.javaToJS(new CustomClass(), scope);
ScriptableObject.putProperty(scope, "CustomClass", wrappedOut);
String s="CustomClass.s='aaa'; \n CustomClass.doSomething=function(args){};";
Object result = cx.evaluateString(scope, s, "<cmd>", 1, null);
因此可以将值更改为 CustomClass.s 但不能更改为方法 doSomething
我收到以下错误:
org.mozilla.javascript.EvaluatorException:无法分配 Java 方法“doSomething”。(#2)
更新 按照评论中的要求,这里是我的完整源代码:
自定义类.java
public class CustomClass {
public String s="Do something now!";
public void doSomething(Object ... v){
System.out.println("do something");
}
}
脚本.java
import org.mozilla.javascript.*;
public class Scripting {
public static void main(String args[])
{
Context cx = Context.enter();
try {
Scriptable scope = cx.initStandardObjects();
Object wrappedOut = Context.javaToJS(new CustomClass(), scope);
ScriptableObject.putProperty(scope, "CustomClass", wrappedOut);
String s="CustomClass.doSomething=function(args){};";
Object result = cx.evaluateString(scope, s, "<cmd>", 1, null);
System.err.println(Context.toString(result));
}catch(WrappedException e){
e.printStackTrace();
} catch(Exception e){
e.printStackTrace();
}finally {
// Exit from the context.
Context.exit();
}
}
}