|
JavaIntegration
Java Integration
Currently xruby provides some ways to make use of the many Java libraries available.You can import Java packages,create a Java object,implement a Java interface,etc.We will list all available features as follows.
#import the specific class require_java 'javax.swing.JFrame' #import the Java packages require_java 'javax.swing.*' require_java 'javax.swing.JFrame'
f = JFrame.new('hello')
require_java 'javax.swing.JFrame'
f = JFrame.new('hello')
f.pack
f.setVisible(true)
#invoke the method defined in Object class
f.toStringimport 'java.lang.System' System.exit(0) require_java 'java.lang.Math' JMath.cos(0) require_java 'java.lang.System'
out = System::out
out.println('ok!')
require_java 'java.lang.Math'
puts JMath.PI
require_java 'java.lang.System'
out = System::out
out.println('ok!')
out.println(123)import 'javax.swing.JFrame'
f = JFrame.new("hello");
# calls setVisible
f.visible= true
# calls getTitle
puts f.titleimport 'com.xruby.runtime.javasupport.AssistantTester'
import 'java.lang.reflect.Array'
import 'java.lang.String'
s = JArray.newInstance(JString, 2)
s[0]='Hello '
s[1]='World!'
AssistantTester.echo(s)
#Suppose that the code of AssistantTester is as follows:
class AssistantTester{
public static void echo(String[] str){
for(String s : str){
System.out.print(s);
}
System.out.println();
}
}import 'java.io.FileInputStream'
import 'java.io.FileNotFoundException'
import 'java.io.IOException'
begin
f = FileInputStream.new('myfile')
rescue FileNotFoundException=>fnfe
puts fnfe.getMessage
rescue IOException=>ioe
puts ioe
endrequire_java 'javax.swing.JFrame'
f = JFrame.new("hello");
# print true
puts f.kind_of?(JFrame)
# print true
puts f.kind_of?(Frame)import 'java.lang.Runnable'
import 'java.lang.Thread'
class MyRunnable < Runnable
def run
puts 'ok'
end
end
r = MyRunnable.new
#prefix a 'J' char in order to escape from name collision
thread = JThread.new(r)
thread.start()Reference |
Sign in to add a comment
Wouldn't it be a good idea to make this match with JRuby's API (or work to support a common subset)? We are talking about the same language after all...