是否可以从JRuby创建Java类并在Java中使用它们?

时间:2011-04-19 18:46:34

标签: java ruby lucene jruby

我正在尝试从JRuby扩展Lucene的Analyzer并从java中使用它。一个简单的分析器看起来像:

class MyAnalyzer < Java::OrgApacheLuceneAnalysis::Analyzer
  def TokenStream (file_name, reader) 
     result = StandardTokenizer.new(Version::LUCENE_CURRENT, reader)
     result = LowerCaseFilter.new(result)
     result = LengthFilter.new(result, 3, 50) 
     result = StopFilter.new(result, StandardAnalyzer.STOP_WORDS_SET)
     result = PorterStemFilter.new(result)
     result
  end 
end

然后我编译它:jrubyc -c /home/camilo/trunk/utils/target/dependency/lucene-core-3.0.2.jar --javac MyAnalyzer.rb并将其打包为jar。

现在,当尝试在java中使用MyAnalyzer时,MyAnalyzerorg.jruby.RubyObject的后代,而不是org.apache.lucene.analysis.Analyzer的后代。

有没有办法让Java将MyAnalyzer视为Analyzer而不是RubyObject?或者这是否超出了JRuby现在可以做的范围?

JRuby版本:jruby 1.6.0 (ruby 1.8.7 patchlevel 330)

1 个答案:

答案 0 :(得分:4)

根据我的理解,我猜你正在尝试创建一个扩展Java类(使用脚本引擎)的JRuby类,并将该类交还给Java。

您的Ruby类可能如下所示:

require 'java'
require 'lucene-core.jar'

java_import 'org.apache.lucene.analysis.Analyzer'
java_import 'org.apache.lucene.analysis.standard.StandardTokenizer'
java_import 'org.apache.lucene.util.Version'
java_import 'org.apache.lucene.analysis.TokenStream'
java_import 'java.io.Reader'

class MyAnalyzer < Analyzer

  def tokenStream(file_name, reader) 
     result = StandardTokenizer.new(Version::LUCENE_CURRENT, reader)
      # ...
  end 
end

然后,您可以在Java中使用此类,如下所示:

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.Reader;
import org.apache.lucene.analysis.Analyzer;

public class RunMyAnalyzer {

    public static void main(String[] args) throws ScriptException, FileNotFoundException {
        String filename = "my-analyzer.rb";

        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("jruby");
        Reader reader = new FileReader(filename);
        engine.eval(reader);

        // Instantiate the JRuby class, and cast the result of eval.
        Analyzer analyzer = (Analyzer) engine.eval("MyAnalyzer.new");

        // You can then use this analyzer like a Lucene Analyzer
    }
}

然后编译并运行:

$ javac -cp .:lucene-core.jar:$JRUBY_HOME/lib/jruby.jar RunMyAnalyzer.java 
$ java -cp .:lucene-core.jar:$JRUBY_HOME/lib/jruby.jar RunMyAnalyzer

这里的关键是JRuby生成一个代理类,然后可以将其转换为Java超类Analyzer