[英]Can I extend a Java class in Oracle's JDK7 JSR223 JavaScript engine?
I'm trying to write JavaScript that will define a class that extends an existing Java class, called from a JSR223 ScriptEngine
. 我正在尝试编写JavaScript,该JavaScript将定义一个扩展现有Java类的类,该类从JSR223
ScriptEngine
调用。 I know that JavaAdapter works for an Interface, but not a Class . 我知道JavaAdapter适用于接口,但不适用于Class 。
ScriptEngine js = new ScriptEngineManager().getEngineByExtension("js");
js.eval("new java.lang.Runnable {run: function() { ... } }"); // works
js.eval("new java.util.TimerTask {run: function() { ... } }"); // throws
I know that's what the docs say I should expect. 我知道这就是我应该期望的文档。 I also know that once I can switch to Nashorn, all this will go away and I'll have lovely access to
Java.extend()
, etc., but for the time being I'm stuck with JDK7. 我还知道,一旦我可以切换到Nashorn,所有这些都将消失,并且可以很好地访问
Java.extend()
等,但是暂时我仍然停留在JDK7上。
Given all that , is there any way to do this? 鉴于所有这些 ,有没有办法做到这一点? I think my fallback will be switching directly to Mozilla's native Rhino bindings, but I'd prefer to keep this as abstract as possible.
我认为我的后备状态将直接切换到Mozilla的本机Rhino绑定,但是我更希望将其保持尽可能抽象。
What does it throw? 它会抛出什么?
jjs> var tt = new java.util.TimerTask {run: function() { print("hello"); }}
jjs> tt.run();
hello
null
I usually skip TimerTask altogether 我通常完全跳过TimerTask
// Daemon flag seems to be ignored.
var timer = new java.util.Timer(false);
timer.schedule(function() print("Hello"), 1000);
// Give timer a chance to run before exit.
java.lang.Thread.sleep(5000);
I think I've figured it out. 我想我已经知道了。 I was under the impression that I could only implement an interface, but it turns out that you can also extend a concrete class -- only abstract classes throw the error I described.
我的印象是我只能实现一个接口,但是事实证明,您还可以扩展一个具体的类-只有抽象类才会抛出我所描述的错误。
ScriptEngine js = new ScriptEngineManager().getEngineByExtension("js");
js.eval("new java.lang.Runnable() {run: function() { ... } }"); // works
js.eval("new java.lang.Thread() {run: function() { ... } }"); // works
js.eval("new java.util.TimerTask() {run: function() { ... } }"); // throws
This is good enough for my needs -- the docs could definitely be clearer, though! 这足够满足我的需求-但是文档绝对可以更清晰!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.