ruby调用java,我可以在ruby中定义Java子类,然后在Java中实例化它吗?

I'd like to define a superclass in Java, then define a subclass in Ruby, then make instances of that subclass in Java. A little something like this:

// Java superclass

package myPkg;

public class Sup{

public Sup(){}

public abstract void foo(String a);

}

--

# Ruby code

include Java

require 'jruby/core_ext'

include_class 'myPkg.Sup'

class RubySub < Java::myPkg.Sup

def foo( a )

puts a;

end

end

RubySub.become_java!

RubySub

--

// Back in Java land

Ruby runtime = Ruby.newInstance();

IRubyObect ro = runtime.evalScriptlet(theRubyCodeAbove);

Class clz = (Class) JavaEmbedUtils.rubyToJava(runtime, ro, Class.class);

clz.newInstance().foo("Hey!");

I've tried the above code, but I get an InstantiationException from the newInstance() call. I want to have the class declared in Ruby at runtime, so e.g. running jrubyc to compile the Ruby code to a Java class definition ahead of time is out. What am I doing wrong here?

I've run through the bottom code segment in the debugger, and I'm definitely getting a RubyClass object returned from the evalScriptlet() call. Maybe there's an extra step involved to turn a RubyClass into a Class?

UPDATE: I have a lead -- apparently become_java! doesn't work if the class is a subclass of a Java class. Is there another way I can do this, or am I just boned?

解决方案

I've come up with a workaround for now, but it's not pretty.

In brief: I can't return RubySub.become_java! (which is nil, because of JRUBY-6105) or try to return RubySub and convert from a RubyClass to a Class.

Instead, I return RubySub.method(:new), which shows up as a RubyMethod. I can call this, and it creates an IRubyObject which is actually an instance of the subclass. This can be cast to the Java superclass using JavaEmbedUtils.rubyToJava(). Like I said, it's not pretty but it works.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值