Tuesday, February 12, 2013

Widgets

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

No comments:

Post a Comment