예전에 깨작깨작 할땐 Java로 했었늗네.. 이번엔 경험삼아 Jruby로 ruby와 java를 혼용해서 써볼까 합니다.
오늘은 Jruby에 대한 이야기를 조금 할까 합니다.
Jruby란?
Jruby는 Ruby와 Java 간의 크로스 개발이 가능하도록 구성된 언어입니다. Ruby에서 Java function을 사용할 수 있고, 반대로 Java에서도 Ruby function을 사용할 수 있어집니다.즉 양방향 엑세스가 가능하다나 소리이지요.
언어 구성 자체는 JVM상단에 Ruby언어를 재 구현한 것이라고 보시면 됩니다.
Ruby에서 Java call
require 'java'
frame = javax.swing.JFrame.new
frame.getContentPane.add javax.swing.JLabel.new('Hello, World!')
frame.setDefaultCloseOperation javax.swing.JFrame::EXIT_ON_CLOSE
frame.pack
frame.set_visible true
Java에서 Ruby call
//Example using JSR 233 Scripting for Java 6
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine rbEngine = mgr.getEngineByExtension("rb");
try {
rbEngine.eval("puts 'Hello World!'");
} catch (ScriptException ex) {
ex.printStackTrace();
}
java gem, jruby 설치
우선 java gem 설치가 필요합니다.> gem install java Fetching: java-0.0.2.gem (100%) Successfully installed java-0.0.2 Parsing documentation for java-0.0.2 Installing ri documentation for java-0.0.2 Done installing documentation for java after 0 seconds 1 gem installed
Jruby도 설치해줍니다.
#> apt-get install jruby Reading package lists... Done Building dependency tree Reading state information... Done The following packages were automatically installed and are no longer required: libdigest-md5-file-perl libdns-export169 libdns169 libhttp-parser2.7.1 libisc-e [.....] 추가 패키지 무지하게 많음..
이제 irb를 통해 루비코드에서 불러보면.. 잘 로드 됩니다.
2.4.2 :003 > require 'java' => true
테스트 코드(버전출력, Swing으로 Gui 구현, jar파일 불러오기
간단하게 Java version 출력해주는 코드를 Java 단에서 불러와봅시다.require ‘java’
java_import java.lang.System
version = System.getProperties["java.runtime.version"]
puts version
> jruby jtest.rb 1.8.0_111-b14
Java swing 을 이용해서 Gui 프로그램을 Jruby로 ruby 코드에서 구현해보면 이렇습니다.
(Swing 싫어했느데.. 다시 하게 될줄이야..)
require 'java'
# Java 코드에선.. import javax.swing.JFrame;
frame = javax.swing.JFrame.new("Window") # Creating a Java JFrame
label = javax.swing.JLabel.new("Hello”)
# Java 코드에서 JLabel label = new Label(“Hello”); 와 같음
frame.add(label) # 나머지 Java method 쓰는건 동일함
frame.setDefaultCloseOperation(javax.swing.JFrame::EXIT_ON_CLOSE)
frame.pack
frame.setVisible(true)
> jruby jruby.rb
Swing 으로 띄우던 것과 같습니다. |
이미 만들어진 라이브러리(jar)를 가져오는건 더더욱 쉽습니다.
그냥 ruby에서 라이브러리 불러오는 것처럼 jar 파일을 require 로 불러와주면 끝납니다.
require 'path/to/mycode.jar'
굿 잘 됩니다 :)
HAHWULSecurity engineer, Gopher and H4cker! |
0 개의 댓글:
Post a Comment