Declaring java package and method signature in JRuby

We can add the package declaration for the java classes generated by JRubyc by using java_package. Just add the following line before the JRuby class declaration

java_package ‘package name’

And also make sure you have included the statement require ‘java’.

require 'java'
java_package 'com.vkslabs.example.ruby'
class MyClass
  def initialize()
  end
  def myfunction(msg)
  	puts msg;
  end
end
MyClass.new.myfunction('Hello JRuby!');

Now once you convert the code using jrubyc you will find that the package structure is automatically created.

Similarly you can declare signatures for java methods using
java_signature ‘put method signature here’

require 'java'
java_package 'com.vkslabs.example.ruby'
class MyClass
  def initialize()
  end
  java_signature 'void myJavaMethod(String msg)'
  def myfunction(msg)
  	puts msg;
  end
end
MyClass.new.myfunction('Hello JRuby!');

Now you can call the new method signature from your java code by creating object for MyClass

import com.vkslabs.example.ruby;
class Test
{
	public static void main(String[] a) {
		MyClass obj = new MyClass();
		obj.myJavaMethod("Hello Jruby from Java");
	}
}

Make sure you include jruby.jar while compiling Test.java

Compiling java code

2312 Total Views 2 Views Today