How to use RJB require ‘rjb’ FooBar = Rjb::import(‘com.example.FooBar’) foobar = FooBar.new foobar.baz = ‘123’ # foobar.setBaz(‘123’) p foobar.baz # foobar.getBaz foobar.snake_method # foobar.snakeMethod Importing class Instantiating class Calling setter Calling getter Calling method
installing RJB sudo JAVA_HOME=/usr/java gem install rjb ・runnable with Sun J2SE 1.4.2 (maybe), 1.5.x, 1.6.x (possible with OpenJDK) (beware 32 / 64 selection) ・buildable with MRI, Rubinius Tested with OSX snow leopard, Windows7, Solaris 10, some Li nux http://rubyforge.org/projects/rjb/ http://github.com/arton/rjb
Why RJB ? • I need glue language so I can easily write the i nteraction between Java classes for testing. • To try and see Java object’s behavior and cal r eflections freely. • At that time there was no JRuby yet. • I like to write and define interfaces. It’s fun.
Who use RJB ? • When migrating to MRI Rails app from Java We b app. – Can use Java business objects on Rails. • Using Java component in Ruby script. – Jakarta POI – JDBC
Design strategy • Start with a simple plan. • Class is Class : can create java instance with .new eg) o = Rjb::import(‘foo.bar.bazClass’).new • Exception as Exception (user request) – Can rescue and read the properties begin …. rescue SQLException => e puts e.error_code end When writing the rescue line, SQLException was not defined (n o need to Rjb::import), dynamic language is real y nice.
Design strategy • JRuby compatibility (suggested by JRuby team) – Transform methods into ruby style – class → Ruby’s , getClass → Java’s • Require expansion (contributed by aronge) require ‘rjb’ require ‘rjbextension’ require ‘/foo/bar/FooBar.jar’ # dynamic jar import(*) p java.lang.Math.abs(-30) #=> 30 no import call * Only effective before loading JVM
writing script for JRuby and Rjb MRI can’t require java but JRuby can require rjb. ------------------------------------------ begin require ‘java’ rescue LoadError require ‘rjb’ require ‘rjbextension’ require ‘jrubybridge’ # def include (vaporware) end Or post a message into RubyForge help forum. http://rubyforge.org/forum/forum.php?forum_id=8190
howto Rjb converts returned value into a proxy object if it was an object. In many case, if the returned value is a primitive type class (ex: java.lang.Integer) , it’s better to convert into a Ruby object (ex: Fixnum). The behavior is controlled by Rjb::primitive_conversion = true default : false
Future plans • Strategy to determine selection of polymorphi c methods • ClassLoader enhancement • Easy way to inherit from existing classes
Conclusion • You can write Ruby script using Java objects. with JRuby or MRI / Rubinius with Rjb.