我正在试验J
Ruby – 从ruby文件生成java.我在ruby中有一个实现Java接口的抽象类,以及扩展它的子类.也是ruby.
我正在遇到问题,如http://jira.codehaus.org/browse/JRUBY-6342所述,其中所有生成的java文件只扩展RubyObject.
我想知道是否有其他人遇到过此问题并有一个解决方法?现在我在每个子类中都使用了java_implement接口,因为它们没有扩展抽象类.
我已经包含了JRUBY-6342中描述问题的片段:
The Java code generated by jrubyc –java does not appear to support Ruby class inheritance. Given the following simple example:
class A
def my_class; self.class.name end
endclass B < A
endThe generated class in B.java inherits from RubyObject rather than A, rendering the B class completely broken in Java.
On a somewhat related note, module inclusion doesn’t seem to work either. A class with include M doesn’t get M’s methods in the generated Java code.
我对Ruby或JRuby的理解中遗漏了什么?
最佳答案 这仍然是一个问题,因为类的jruby编译器
still produces RubyObject.
我所知道的唯一解决方法是使用Java的JRuby ScriptEngine来评估你的JRuby代码.例如,这是一些JRuby代码:
require 'java'
java_import 'javax.swing.JFrame'
java_import 'javax.swing.JButton'
class MyFrame < JFrame
def initialize
super('Test')
content_pane.add(JButton.new("Hello"))
pack()
end
end
然后可以从这样的Java类调用此代码:
import javax.swing.JFrame;
import javax.script.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("jruby");
Reader reader = new FileReader("myframe.rb");
engine.eval(reader);
// Instantiate the JRuby class, and cast the result of eval.
JFrame frame = (JFrame) engine.eval("MyFrame.new");
frame.setVisible(true);
}
}
在这里,eval返回的对象可以像你期望的那样被转换为JFrame.有关该问题,另请参见this question.