Showing posts with label Ruby. Show all posts
Showing posts with label Ruby. Show all posts

Tuesday, February 12, 2013

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'.

[ruby]
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!');
[/ruby]

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'

[ruby]
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!');
[/ruby]

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

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


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

Compiling java code

Converting JRuby to Java

Now that we know how to write a basic JRuby code lets see how to convert the JRuby code in to Java code. JRuby comes with JRubyc a cross compiler that does the magic!

Convert to Java code
Compile JRuby in to Java Source file

Convert JRuby Java class files
Compile JRuby in to Java class file

Okay great! now you have Java source class for your JRuby class but what if you want to declare package and method signature for the generated java class?

Introduction to JRuby

JRuby
JRuby is an implementation of Ruby which runs on top of Java Virtual Machine. JRuby code can be embedded in Java code and your JRuby code can interact with Java Objects and has access to every Java API.

Why to use JRuby?
Ruby being a scripting language is dynamic and much faster than Java. There are lot of things that can be easily accomplished in Ruby for example I found that parsing & scraping HTML is much easier and faster in Ruby using HPricot. As a Java programmer and you can write part of your application in JRuby and then either embed this in your Java code or use JRubyC compiler to convert your JRuby code in to Java.

Your first JRuby program

[ruby]
require 'rubygems'
class MyClass
def initialize()
end
def myfunction(msg)
puts msg;
end
end
MyClass.new.myfunction('Hello JRuby!');
[/ruby]

Executing the above code can be done using the following command
jruby