2011-04-19 61 views
4

我試圖從JRuby擴展Lucene的Analyzer並從java中使用它。一個簡單的分析看起來像:是否可以從JRuby創建Java類並在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並將其打包作爲一個罐子。

現在,欲以MyAnalyzer回到Java時,MyAnalyzerorg.jruby.RubyObject後裔,而不是org.apache.lucene.analysis.Analyzer

有沒有辦法讓Java對待MyAnalyzer作爲Analyzer而不是RubyObject?或者這種方式超出了JRuby現在可以做的範圍?

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

回答

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生成一個代理類,然後可以將其轉換爲Analyzer ,Java超類。

相關問題