If you can make a direct attachment, use JavaEmbedUtils and call eval on the line of ruby ββcode that defines your proc / block / clos or your ruby ββcode that implements an interface where certain methods return your proc / block / close. An incredibly contrived example to summarize the two numbers below:
SampleApp.java
import org.jruby.Ruby; import org.jruby.RubyRuntimeAdapter; import org.jruby.RubyFixnum; import org.jruby.RubyProc; import org.jruby.javasupport.JavaEmbedUtils; import org.jruby.runtime.Block; import org.jruby.runtime.ThreadContext; import java.util.ArrayList; class SampleApp { public static void main(String[] args) {
SomeInterface.java
interface SomeInterface { org.jruby.RubyProc getAdditionProc(); }
SomeInterfaceImpl.rb
require 'java' class SomeInterfaceImpl include Java::SomeInterface java_signature 'org.jruby.RubyProc getAdditionProc()' def getAdditionProc() return Proc.new { |a, b| a + b } end end
And here is how you can test:
javac -classpath jruby.jar SomeInterface.java jrubyc --javac -cp . SomeInterfaceImpl.rb javac -cp jruby.jar:. SampleApp.java java -cp jruby.jar:. SampleApp
Literature:
https://github.com/jruby/jruby/wiki/DirectJRubyEmbedding
http://tommy.chheng.com/2010/06/20/call-a-jruby-method-from-java/
source share