Skip to content

Instantly share code, notes, and snippets.

@adilsoncarvalho
Created July 12, 2011 01:12
Show Gist options
  • Save adilsoncarvalho/1077172 to your computer and use it in GitHub Desktop.
Save adilsoncarvalho/1077172 to your computer and use it in GitHub Desktop.
Examples about how to access java classes with jruby
package e7r;
/**
* Simple calculator class to be used inside jruby
*/
public class Calculator {
/**
* Adds two integer numbers
* @param a First value
* @param b Second value
* @return The sum of two values
*/
public int sum(int a, int b) {
return a + b;
}
}
#
# First you must require java to gain some special powers
# Remember that this works only with jruby!
#
require 'java'
#
# Then require your jar file. Note that you can't do something like
# import SmallestJar.*. You must require each jar by yourself.
#
require 'SmallestJar'
# Some ways of consuming java classes inside jruby
#
# 1. Let's do it the hard way: using full package name every time
# - remember to always start with a Java:: and then the package namespace
# - some namespaces like org, com, etc. are mapped directly
#
calculator = Java::e7r.Calculator.new
puts calculator.sum(10, 20)
#
# 2. Let's do it the messy way: including the package in the current context
#
include_class Java::e7r.Calculator
calculator = Calculator.new # look mama, no namespaces
puts calculator.sum 10, 20
#
# 3. The man's way: Create a module to put the classes (via include_package)
#
module E7R
include_package 'e7r'
end
calculator = E7R::Calculator.new
puts calculator.sum 10, 20
# EOF
# two steps to create a jar manually
javac Calculator.java
jar cvf SmallestJar.jar Calculator.class
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment