Java Rhino 允许从安全上下文访问 java

Java Rhino allow access to java from safe Context

我想创建沙盒 java 脚本环境并限制对 java 类 的所有访问,但我指定的访问。我试图通过使用 Context.initSafeStandardObjects()

创建 Context 来实现这一点

有没有办法让其他 类 被 java 脚本使用? 如果我使用 Context.initStandardObjects()

创建上下文

我可以访问所有 java 类 这不是我想要的。

我找到了解决办法。您可以使用以下方法将 java class 的实例添加到 java 脚本中:

Object wrappedTest = Context.javaToJS(test, scope);
ScriptableObject.putProperty(scope, "test", wrappedTest); //Where text here is name of the variable

你可以在 java 脚本中使用这个 class 的方法,即使你使用 initSafeStandardObjects

初始化上下文
Object result = cx.evaluateString(scope, "test.sampleMethod()", "<cmd>",1, null);
System.out.println(cx.toString(result));