加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何使用JRuby在Java中创建Ruby模块?

发布时间:2020-12-17 03:06:16 所属栏目:百科 来源:网络整理
导读:在 Ruby中,我可以有一个类似的模块: module Greeter def greet print "Hello" endend 我的班级可以得到这样的问候方法: class MyClass include Greeterendobj = MyClass.newobj.greet 现在,我想让我的模块Greeter用Java实现.我正在使用JRuby.我不确定如何
在 Ruby中,我可以有一个类似的模块:

module Greeter
  def greet
    print "Hello"
  end
end

我的班级可以得到这样的问候方法:

class MyClass
  include Greeter
end

obj = MyClass.new
obj.greet

现在,我想让我的模块Greeter用Java实现.我正在使用JRuby.我不确定如何用Java创建一个Ruby模块(这样我可以正常包含).

我曾经做过Java接口.将它包含在我的Ruby类中并不会抛出错误,但它实际上并不是一回事,因为模块似乎实现了这些方法,而Java接口却没有.

解决方法

以下是如何使用Java扩展实现与上面完全相同的代码.

这里的所有内容都是默认的包级别(没有包),如果你想让包只更改模块名称.

首先,创建Greeter类:

import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;

public class Greeter {

    @JRubyMethod
    public static void greet( ThreadContext context,IRubyObject self ) {
        System.out.printf("Hello from %s%n",self);
    }

}

然后你需要GreeterService来加载它:

import org.jruby.Ruby;
import org.jruby.RubyModule;
import org.jruby.runtime.load.BasicLibraryService;

import java.io.IOException;

public class GreeterService implements BasicLibraryService {

    @Override
    public boolean basicLoad(final Ruby runtime) throws IOException {
        RubyModule greeter = runtime.defineModule(Greeter.class.getSimpleName());
        greeter.defineAnnotatedMethods(Greeter.class);

        return true;
    }

}

通过定义这些类,以下是如何在JRuby脚本中使用它们:

require 'target/jruby-example.jar'
require 'greeter'

class MyClass
  include Greeter
end

obj = MyClass.new
obj.greet

jruby-example.jar包含上面编译和打包的类.这里没有什么可做的,现在你有了可以包含在任何地方的模块.更大的例子,只需检查Enumerable模块的实现方式.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读