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 th开发者_Python百科is possible? And, if so, how do you do it?
Yes, you can; previous poster is wrong. See the documentation for JavaAdapter.
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:
- 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. - Define a naming convention that relates abstract classes to the wrapper, e.g.
foo.MyAbstractClass
corresponds tofoo.MyAbstractClassDynamicLangWrapper
. - Roll a
ClassLoader
that implements findClass to recognize that naming convention and to generate the class bytes and calls defineClass - 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.
精彩评论