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

214 Views Asked by At

There is a Java interface Job:

interface Job{
...
}

and a JRuby class SimpleJob that implements it:

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. How do I do this?

2

There are 2 best solutions below

0
kares On BEST ANSWER

"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 :

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

assuming you obtained a org.jruby.Ruby runtime instance

0
Nadir On

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? 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