如何从 Ruby 1.8 或 1.9 调用 Java API [英] How to call Java API from Ruby 1.8 or 1.9

查看:32
本文介绍了如何从 Ruby 1.8 或 1.9 调用 Java API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个 JRuby 工作 代码(从 Keith 的博客),它封装了 SAXON xslt 处理器 API.

I've this JRuby working code (stolen from Keith's Blog), which wraps the SAXON xslt processor API.

现在,我想知道我是否可以以及如何在 Ruby 框架中封装相同的 API?

请告诉我这个问题是无意义的还是可以以某种方式改进.

Please tell me if this question is non-sense or if it can be improved in some way.

这是想要的 API.

这是我使用的 JRuby 代码:

And this is the JRuby code I'm using:

require 'java'
module JXslt
  include_class "javax.xml.transform.TransformerFactory"
  include_class "javax.xml.transform.Transformer"
  include_class "javax.xml.transform.stream.StreamSource"
  include_class "javax.xml.transform.stream.StreamResult"
  include_class "java.lang.System"

  class XsltProcessor
    def transform(xslt,infile,outfile)
      transformer = @tf.newTransformer(StreamSource.new(xslt))
      transformer.transform(StreamSource.new(infile), StreamResult.new(outfile))
    end
  end # XsltProcessor
  class Saxon < XsltProcessor
    TRANSFORMER_FACTORY_IMPL = "net.sf.saxon.TransformerFactoryImpl"
    def initialize
      System.setProperty("javax.xml.transform.TransformerFactory", TRANSFORMER_FACTORY_IMPL)
      @tf = TransformerFactory.newInstance
    end
  end
end 

推荐答案

如上所述,您不能直接从 Ruby 运行时执行此操作,从 Ruby 调用 Java 需要您在 JRuby 上或使用 C 间接调用 Java/C++ JVM API,允许您从 C 调用 Java 代码.

As commented above, you can not do this directly from the Ruby runtime, calling Java from Ruby requires you to be either on JRuby or call Java indirectly using the C/C++ JVM API that allows you to call Java code from C.

第一个选项可能是使用 Ruby Java Bridge 为您完成大部分繁重的工作(它的功能作为 Ruby-to-C-to-Java 包装器).

The first option is possibly using Ruby Java Bridge that does most of the heavy lifting for you (it functions as a Ruby-to-C-to-Java wrapper).

如果 RJB 不适合您,您也可以使用 C 语言中的 JVM API 直接构建包装器(此处的示例 ),然后您可以使用 FFI 从 Ruby 调用它.

If RJB doesn't work for you, you can also build your wrapper directly by using the JVM API in C ( example here ) and then you could call it from Ruby using FFI.

但是除非您真的需要使用 C-Ruby (MRI),否则我强烈建议您避免上述任何方法而只使用 JRuby,因为深入研究本机代码将导致可能的段错误、内存管理问题和所有上述选项强制您在单线程中运行,而您可以使用 JRuby 构建多线程解决方案.

But unless you really need to use the C-Ruby (MRI) I would greatly recommend you to avoid any of the approaches above and just use JRuby, as delving into native code will lead to possible segfaults, memory management issues and all options above force you to run in a single thread, while you could build a multi-threaded solution by using JRuby.

这篇关于如何从 Ruby 1.8 或 1.9 调用 Java API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆