Wednesday, October 27, 2010

JRuby include_package doesn't define constants

Using include_package in a module to import java classes in JRuby usually works as expected, but not always. Try this code in JRuby 1.5.3
$ jruby ns.rb
ns.rb:

require 'java'
require 'pp'

class Rule
end

module MyCompany
module JavaModel
include_package 'com.model'
end
end

pp MyCompany::JavaModel.const_get('Foo')
pp MyCompany::JavaModel.const_get('Rule')
You can simple create two java files and compile them using javac.
com/model/Foo.java:

package com.model;
public class Foo {
}

com/model/Rule.java:
package com.model;
public class Rule {
}
$ javac com/model/Foo.java
$ javac com/model/Rule.java
Here is the output:
Java::ComModel::Foo
Rule
Why the second line is not Java::ComModel::Rule? include_package just overrides const_missing instead of defining constants in module MyCompany::JavaModel. When you call MyCompany::JavaModel.const_get("Rule"), the constant "Rule" is defined, const_missing is skipped.

Using java_import will work correctly although you have to list each class.

module MyCompany
module JavaModel
java_import 'com.model.Foo'
java_import 'com.model.Rule'
end
end
Note: if you use java_import outside the module, you will overwrite the constant Rule.

No comments:

Post a Comment