简体   繁体   English

如何实例化在Java中实现Java接口的JRuby类

[英]How can I instantiate a JRuby class that implements a Java interface in Java

There is a Java interface Job: 有一个Java接口Job:

interface Job{
...
}

and a JRuby class SimpleJob that implements it: 和一个实现它的JRuby类SimpleJob:

class SimpleJob
require org.quartz.Job
...
end

I need to (from a Java class) instantiate the SimpleJob class using the javax.script.ScriptEngine class, and get its class object. 我需要(从Java类)使用javax.script.ScriptEngine类实例化SimpleJob类,并获取其类对象。 How do I do this? 我该怎么做呢?

I'm not sure if you can instate it. 我不确定是否可以恢复原状。 Why you just dont create a script that does what you want and then use the SciptEngine to execute the script? 为什么不创建自己想要执行的脚本,然后使用SciptEngine执行脚本呢? Like so 像这样

ScriptEngineManager m = new ScriptEngineManager();
ScriptEngine rubyEngine = m.getEngineByName("jruby");
try {  
  FileReader f = new FileReader("yourscript.rb");
  engine.eval(f);
} catch (javax.script.ScriptException e) {
    ...
} 

Also take a look at this, maybe it will help you https://github.com/jruby/jruby/wiki/DirectJRubyEmbedding 还请看一下,也许会对您有所帮助https://github.com/jruby/jruby/wiki/DirectJRubyEmbedding

"easiest" way is doing an eval : “最简单”的方法是进行评估:

IRubyObject instance = (IRubyObject) rubyEngine.eval("SimpleJob.new");

to access the class and "call" it by hand : 访问该类并手动“调用”它:

RubyClass klass = (RubyClass) rubyEngine.eval("SimpleJob");
klass.callMethod("new");

NOTE: it's also possible to achieve the same using JRuby's "direct" API : 注意:也可以使用JRuby的“直接” API实现相同的目的:

runtime.getClass("SimpleJob").callMethod("new");

assuming you obtained a org.jruby.Ruby runtime instance 假设您获得了org.jruby.Ruby 运行时实例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM