Hi,
Ideally I would like to have a Ruby script which creates an instance
which when returned from the script implements a particular interface.
Example
final ScriptingContainer sc = new
ScriptingContainer(LocalContextScope.SINGLETON,
LocalVariableBehavior.TRANSIENT);
final Object r = sc.runScriptlet(“m=Object.new;class <<m;p
self;java_implements java.lang.Runnable;java_signature ‘void
run()’\ndef run() puts ‘done’ end end;m”);
sc.callMethod(r, “run”); // works
((Runnable) r).run(); // fails at the cast
I searched around but only found
http://www.ruby-forum.com/topic/214760#932016
http://tommy.chheng.com/index.php/2010/06/call-a-jruby-method-from-java/
But these only explain how to make a class implement a Java interface.
Is it possible at all to make a singleton class implement an interface
and make that accessible directly from Java? The only way I found so
far is by using a Proxy
final InvocationHandler ih = new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
return args == null ? sc.callMethod(r, method.getName()) :
sc.callMethod(r,
method.getName(),
args);
}
};
final Runnable r2 = (Runnable)
Proxy.newProxyInstance(r.getClass().getClassLoader(),
new
Class<?>[] { Runnable.class },
ih);
r2.run();
But then I don’t need the implements stuff in Ruby code. Is there any
other way?
Btw, I found this but am unsure in how far this is related:
Kind regards
robert
–
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/