如何使用 Rhino 将 Java 类中的方法添加为 Javascript 中的全局函数?

发布于 2024-08-27 13:57:14 字数 686 浏览 5 评论 0原文

我有一个简单的Java类,它有一些方法:

public class Utils {
    public void deal(String price, int amount) {
        // ....
    }
    public void bid(String price, int amount) {
        // ....
    }
    public void offer(String price, int amount) {
        // ....
    }
}

我想创建这个类的一个实例,并允许Javascript代码直接调用这些方法,如下所示:

deal("1.3736", 100000);
bid("1.3735", 500000);

我现在能想到的唯一方法是使用

ScriptEngine engine = new ScriptEngineManager().getEngineByName("js");
engine.put("utils", new Utils());

然后使用Javascript 代码中的 utils.deal(...) 。我还可以在 Javascript 中为每个方法编写包装函数,但应该有一种更简单的方法来自动为类的所有公共方法执行此操作。

I have a simple Java class that has some methods:

public class Utils {
    public void deal(String price, int amount) {
        // ....
    }
    public void bid(String price, int amount) {
        // ....
    }
    public void offer(String price, int amount) {
        // ....
    }
}

I would like to create an instance of this class and allow the Javascript code to call the methods directly, like so:

deal("1.3736", 100000);
bid("1.3735", 500000);

The only way I could figure out for now was to use

ScriptEngine engine = new ScriptEngineManager().getEngineByName("js");
engine.put("utils", new Utils());

and then use utils.deal(...) in the Javascript code. I can also write wrapper functions in Javascript for each method, but there should be a simpler way to do this automatically for all the public methods of a class.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

§对你不离不弃 2024-09-03 13:57:14

我对 Rhino 不太熟悉,但是这样的东西应该可以工作:

for(var fn in utils) {
  if(typeof utils[fn] === 'function') {
    this[fn] = (function() {
      var method = utils[fn];
      return function() {
         return method.apply(utils,arguments);
      };
    })();
  }
}

只需循环 utils 的属性,并为每个函数创建一个调用它的全局函数。

编辑:我在 Groovy 脚本中得到了这个工作,但我必须在绑定中设置 utils,而不是像代码中那样在引擎上设置:

import javax.script.*

class Utils {
   void foo(String bar) {
      println bar
   }   
}

ScriptEngine engine = new ScriptEngineManager().getEngineByName("js");

engine.eval("""
for(var fn in utils) {
  if(typeof utils[fn] === 'function') {
    this[fn] = (function() {
      var method = utils[fn];
      return function() {
         return method.apply(utils,arguments);
      };
    })();
  }
}

foo('foo'); // prints foo, sure enough
""",new SimpleBindings("utils":new Utils()))

I'm not real familiar with Rhino, but something like this should work:

for(var fn in utils) {
  if(typeof utils[fn] === 'function') {
    this[fn] = (function() {
      var method = utils[fn];
      return function() {
         return method.apply(utils,arguments);
      };
    })();
  }
}

Just loop over the properties of utils,and for each one that is a function, create a global function that calls it.

EDIT: I got this working in a Groovy script, but I had to set utils in the bindings, not on the engine like in your code:

import javax.script.*

class Utils {
   void foo(String bar) {
      println bar
   }   
}

ScriptEngine engine = new ScriptEngineManager().getEngineByName("js");

engine.eval("""
for(var fn in utils) {
  if(typeof utils[fn] === 'function') {
    this[fn] = (function() {
      var method = utils[fn];
      return function() {
         return method.apply(utils,arguments);
      };
    })();
  }
}

foo('foo'); // prints foo, sure enough
""",new SimpleBindings("utils":new Utils()))
此生挚爱伱 2024-09-03 13:57:14

我不确定使用 JSR-223 API 会如何工作,但使用 Rhino API,您可以使用要添加的方法创建一个 FunctionObject ,如下所示。

Class[] parameters = new Class[] { String.class, Integer.class };
Method dealMethod = Utils.class.getMethod("deal", parameters);
engine.put("deal", new FunctionObject("deal", dealMethod, scope));

该文档位于 https://www.mozilla.org /rhino/apidocs/org/mozilla/javascript/FunctionObject.html

您可能需要引用 Rhino 库来访问 FunctionObject 类,并且我不确定如何使用 JSR-223 API 获取 scope 对象(尽管, null 可能会起作用)。

I'm not sure how this would work using the JSR-223 API, but with the Rhino API, you can create a FunctionObject with the method you want to add like this.

Class[] parameters = new Class[] { String.class, Integer.class };
Method dealMethod = Utils.class.getMethod("deal", parameters);
engine.put("deal", new FunctionObject("deal", dealMethod, scope));

The documentation is available at https://www.mozilla.org/rhino/apidocs/org/mozilla/javascript/FunctionObject.html.

You might need to reference the Rhino library to access the FunctionObject class, and I'm not sure how you would get the scope object with the JSR-223 API (although, it's possible that null would work).

迷途知返 2024-09-03 13:57:14

如果您使用 rhino API 而不是 ScriptEngine API,如本答案所述:https://stackoverflow.com/a/ 16479685/1089998

与 Noah 的答案相比,我更喜欢这种方法,因为这意味着您不需要在每次执行之前执行随机的 javascript 代码。

我这里有一个工作示例:

https://github.com/plasma147/rhino-play

This is possible if you use the rhino API rather than the ScriptEngine API as explained in this answer: https://stackoverflow.com/a/16479685/1089998.

I prefer this approach over Noah's answer as it means you don't need to execute random javascript code before each execution.

I have a working example here:

https://github.com/plasma147/rhino-play

做个少女永远怀春 2024-09-03 13:57:14

使用 Java Lambda(从 1.8 开始),实际上可以这样做:

ScriptEngine engine = new ScriptEngineManager().getEngineByName("js");
BiConsumer<String, Integer> deal = Utils::deal
engine.put("deal", deal);

With Java Lambdas (so since 1.8) it is actually possible to just do this:

ScriptEngine engine = new ScriptEngineManager().getEngineByName("js");
BiConsumer<String, Integer> deal = Utils::deal
engine.put("deal", deal);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文