CSC/ECE 517 Fall 2012/ch1 1w6 pp

From PG_Wiki
Jump to: navigation, search

Mixing static and dynamic Object Oriented code helps us achieve a peaceful integration of static and dynamic aspects in the same language. This page will mention some of the difficulties which are observed when these two types of object orientation are mixed. We will then give a practical example of this using JRuby. JRuby is a programming language which is a mix of Java and Ruby. We will cover the different implementations of JRuby with examples.



Object oriented programming is a programming paradigm using "objects" – usually instances of a class – consisting of data fields and methods together with their interactions to design applications and computer programs. In static object orientation, this instantiation is static, that is the class to which an object belongs is defined before the execution of the code. This gives a strong binding of the objects, and ensures that the correct instance variables and methods are accessed by that object. In Dynamic object orientation, also known as interpreted object orientation, there is no fixed type. The type the object belongs to is determined during runtime, hence that gives additional flexibility. Static typing should be used where possible, dynamic typing when needed.


JRuby is the Ruby Programming Language on the JVM. Ruby is a reflective, dynamic, and interpreted object-oriented scripting language. JRuby is a Java programming language implementation of the Ruby language syntax with all the core libraries plus the standard libraries. With JRuby, you get all of the advantages of Ruby plus access to the full range of Java platform functionality. This can be achieved using the following two flavors.

Some examples where this integration can be done are:

Difficulties in mixing static and dynamic object oriented code

There can be some issues in mixing static and dynamic object oriented code.

Advantages of JRuby

Advantages of JRuby over Ruby

Advantages of JRuby over Java

JRuby Explained

In addition to the advantages mentioned in the above section, some other features of JRuby are:

Let us see the two implementations of JRuby.

Driving Java from Ruby

This involves calling Java methods from Ruby code. This includes adding some Java functionality in the Ruby code. The final code will be run on the JVM. Ruby code can load and interact with Java libraries. As a simple example we can use an ArrayList from Java and integrate it with the Ruby code as seen below:

require ‘java’

list =

list << ‘List of’
list << 3 
list << :assorted_items

list.each do |item|
puts “#{item.class}: #{item}”

Instead of just requiring a specific class you can also require the entire package. This can be done as follows:

module JavaLangDemo
  include_package "java.lang"
  # alternately, use the #import method
  import "java.lang"

One has to be careful in doing this as name conflicts in both Ruby and Java can result in losing the Ruby functionality. For example, if a File object is created using Java’s class, then the Ruby constant File becomes useless.

newfile ="file.txt")

and then using:'README', 'r') {|f| puts f.readline }

This will give the error - NoMethodError: private method `open' called for Java::JavaIo::File:Class

This situation can be avoided by including the package in the module definition and then using that module scope to create a new file using the File object.

newfile ="file.txt")

JRuby will forward any option to the underlying Java runtime if you preface it with -J.

Driving Ruby from Java

There are three ways for using the JRuby Interpreter from Java namely, Embedding JRuby, using JSR 223 and the Bean Scripting Framework.

Embedding JRuby

Embed Core[2] is the main embedding API that ships with JRuby. This API offers a great deal of interoperability. You can call a Ruby method, crunch the results in Java, and hand data back into Ruby. The following code shows an example of embedding Ruby in Java.

import java.util.ArrayList;
import org.jruby.Ruby;
import org.jruby.RubyRuntimeAdapter;
import org.jruby.javasupport.JavaEmbedUtils; 

public class MyEmbedRubyExample {
    public static void main(String[] args) throws Exception {
   	    // Create runtime instance
        Ruby runtime = JavaEmbedUtils.initialize(new ArrayList());
        RubyRuntimeAdapter evaler = JavaEmbedUtils.newRuntimeAdapter();

        evaler.eval(runtime, "puts 1+2");

        // Shutdown and terminate instance

To run the above code you need to include jruby.jar in the classpath. This jar is present in the lib folder of the JRuby installation directory. The above example outputs "3" as expected.

JSR 223, Scripting for the Java Platform

This provides an API framework for calling scripting code from within a Java application and passing data between the application and the script. These features make it possible to combine existing scripts with Java applications and to extend a Java application with general-purpose scripts that other Java applications can also use. JSR 223 Scripting APIs are available in JDK 6 software, and by default, the APIs support the JavaScript programming language. The JSR 223 Scripting APIs can be used with any JSR 223-compliant scripting engine such as JRuby.

The steps are:

import javax.script.*;

public class jrubytry {
    public static void main(String[] args) throws Exception {
        ScriptEngineManager factory = new ScriptEngineManager();

        // Create a JRuby engine.
        ScriptEngine engine = factory.getEngineByName("jruby");

        // Evaluate JRuby code from string.
        try {
        } catch (ScriptException exception) {

The above program prints "Hello".

The Bean Scripting Framework (BSF)

This is another way to call scripting code from within a Java application.

The Bean Scripting Framework, when used with JRuby, will allow you to conveniently to pass your own Java objects to your JRuby script. You can then use these objects in JRuby, and changes will affect your Java program directly. To run a JRuby script using BSF, you must first copy the BSF.jar file into your JAVA_HOME/lib/ext/ folder. Then, try the following:

import org.jruby.Ruby.*;
import org.jruby.*;
import org.jruby.javasupport.bsf.*;
import org.apache.bsf.BSFException;
import org.apache.bsf.BSFManager;
JLabel mylabel = new JLabel();
                                   new String[] { "rb" });

BSFManager manager = new BSFManager();

/* Import an object using declareBean then you can access it in JRuby with $<name> */
manager.declareBean("label", mylabel, JFrame.class);
manager.exec("ruby", "(java)", 1, 1, "$label.setText(\"This is a test.\")");

Conversion of Types

When calling Java from JRuby, primitive Ruby types are converted to default boxed Java types. The table below shows this conversion. For example if we have a ruby method that returns a string object then we can convert it into a java.lang.String object on the Java side. The table shown below provides a quick overview of the mapping of types:

Ruby Type Java Type
"foo" java.lang.String
1 java.lang.Long
1.0 java.lang.Double
true, false java.lang.Boolean
1 java.math.BigInteger

When primitive Java types are passed to JRuby they are converted to the following Ruby types:

Java Type Ruby Type
public String String
public byte Fixnum
public short Fixnum
public char Fixnum
public int Fixnum
public float Float
public double Float

Difficulties with JRuby

Larger memory footprint and startup time - Difficulty over Java.

A single JRuby instance needs more memory than a single Ruby instance, but in a typical production server environment with multiple mongrels, memory can be shared so that we can expect a lower or at least equal memory usage in total. JRuby’s startup time is higher than MRI, but once the JVM has “warmed up” after a few minutes, it usually runs faster than MRI.

No native C extension - Difficulty over Ruby.

Due to the nature of Java, it is impossible to run any native extension. So there are several gems that don’t work since they rely on a C extension. However, there’s ongoing effort to create alternative gems that are compatible to JRuby. E.g. mongrel uses a native C extension, but if you install the mongrel gem using JRuby, it automatically installs a java-enhanced version.

JRuby is not technically complete

It’s told that there are cases where JRuby is not 100% compatible with MRI. However, big frameworks like Rails are tested with JRuby.


The JRuby interpreter combines Ruby's simplicity and ease of use with Java's extensive libraries and technologies, a potent blend that opens new possibilities for Ruby, Rails, and Java. JRuby combines a lot of advantages of Java and Ruby by enabling us to reopen Java classes, mixing Java interfaces in Ruby, letting JRuby classes implement more than one Java interface by mixing the interfaces in the classes, catching the native Java exceptions and throwing them via Ruby code etc. There are three ways of calling Ruby from Java namely embedding JRuby, using JSR 223 and by using the bean scripting framework and this provides better flexibility to the programmer. Thus mixing static and dynamic code combines the power of dynamic languages with the stability of static languages.


  12. Kutner, Joe (August 22, 2012), Static Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between Programming Languages

Further Reading

Charles O Nutter, Thomas Enebo, Nick Sieger, Ola Bini, and Ian Dees, Using JRuby: Bringing Ruby to Java, 2011

Personal tools