你能从 JavaScript 扩展抽象 Java 类吗?

发布于 2024-11-17 13:39:51 字数 156 浏览 3 评论 0原文

我正在开发一个大量使用 javax.script.* 包的项目。我有一种情况,我想创建扩展抽象 Java 类的 JavaScript 对象,就像您可以使用 Invocable.getInterface 来创建实现 Java 接口的 JavaScript 对象一样。这可能吗?如果是这样,你会怎么做?

I'm working on a project that makes really heavy use of the javax.script.* packages. I have a situation where I would like to create JavaScript objects that extend an Abstract Java Class, much like you can use Invocable.getInterface to make JavaScript objects that implement Java interfaces. Is this possible? And, if so, how do you do it?

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

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

发布评论

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

评论(2

逆光飞翔i 2024-11-24 13:39:51

是的,你可以;之前的海报是错误的。请参阅 JavaAdapter 文档

Yes, you can; previous poster is wrong. See the documentation for JavaAdapter.

妄司 2024-11-24 13:39:51

除非您想在运行时生成字节码(使用 BCEL 如下),否则不行。您可以使用 代理类 通过接口来完成此操作,但是有与抽象类没有等价物。

如果您确实想尝试 BCEL,最好的策略是这样做:

  1. 编写一个方法,使用 BCEL 为扩展抽象类并委托每个抽象的新类生成字节码的 byte[] JavaScript 方法。
  2. 定义一个将抽象类与包装器相关联的命名约定,例如,foo.MyAbstractClass 对应于foo.MyAbstractClassDynamicLangWrapper
  3. 滚动一个实现 findClass 识别命名约定并生成类字节并调用 defineClass
  4. 确保您的脚本语言使用自定义类加载器来解析脚本中的类名。我认为在Rhino中你使用 setApplicationClassLoader 但我不确定。

Unless you want to go the route of generating bytecode at runtime (using BCEL as below) then no. You can do it with interfaces using proxy classes but there is no equivalent for abstract classes.

If you really want to try BCEL, your best strategy is to do this:

  1. Write a method that uses BCEL to generate a byte[] of bytecode for a new class that extends the abstract class and delegates every abstract method to JavaScript.
  2. Define a naming convention that relates abstract classes to the wrapper, e.g. foo.MyAbstractClass corresponds to foo.MyAbstractClassDynamicLangWrapper.
  3. Roll a ClassLoader that implements findClass to recognize that naming convention and to generate the class bytes and calls defineClass
  4. Make sure your scripting language uses your custom classloader to resolve class names in scripts. I think in Rhino you use setApplicationClassLoader but I'm not sure.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文