JRuby String doesn't seem to be compatible with Java String

| | Comments (0) | TrackBacks (0)

JRuby String 즉, JRuby 상에서의 Ruby String과 Java String이 서로 호환되지 않는 문제를 발견했다. ASCII의 경우에는 별 문제가 없지만, 한글의 경우에는 깨지는 문제가 발생한다. JRuby 사용자가 별로 없어서 이 문제가 내 환경에 국한된 문제인지 실제로 JRuby의 문제인지 확인은 할 수 없다. JRuby 코드를 약간 들여다보아야 할 것 같다.

이 문제를 테스트하기 위해서는 다음의 Ruby 코드를 사용하면 된다. Java String은 System.out.println으로 출력했을 때만, Ruby String은 puts로 출력했을 때만 정상적으로 출력된다. 서로 호환이 된다면, 모두 정상적으로 출력되어야할 것이다.

require 'java'

include_class 'Foo'
include_class 'java.lang.System'

java_string = Foo::getString # yields 'meme메롱' in java.lang.String form
puts java_string
System.out.println java_string

ruby_string = 'meme메롱'
puts ruby_string
System.out.println ruby_string

다음 코드는 위의 Ruby 코드에서 사용하는 Java 클래스인 Foo 클래스.

import java.lang.String;

public class Foo {
   public static String getString() {
      return new String("meme메롱");
}
}

이 문제를 피해가기 위한 한가지 workaround는 ASCII 문자로 된 intermediate form을 두고 Java String과 Ruby String을 서로 변환하는 것이다. intermediate form은 어떤 것을 사용해도 되지만 percent encoding을 사용하여, 다음과 같은 코드를 사용할 수 있다.

require 'java'
require 'cgi'

include_class 'java.net.URLEncoder'
include_class 'java.net.URLDecoder

class StringTranslator
   def self.to_ruby_string(java_str)
      CGI.unescape(URLEncoder.encode(java_str, "UTF-8"))
end

def self.to_java_string(ruby_str)
      URLDecoder.decode(CGI.escape(ruby_str), "UTF-8")
end
end

 

Categories

0 TrackBacks

Listed below are links to blogs that reference this entry: JRuby String doesn't seem to be compatible with Java String.

TrackBack URL for this entry: http://lastmind.net/mt/mt-tb.cgi/361

Leave a comment

About this Entry

This page contains a single entry by Joseph, Jang published on February 21, 2007 5:27 PM.

Calling a Java method with variable number of arguments in JRuby was the previous entry in this blog.

Refactoring: Improving the Design of Existing Code is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Powered by Movable Type 4.1