您可以从这里下载完整的 jruby .jar 文件
然后我就抓了一些示例代码:
import org.jruby.*;
import org.jruby.javasupport.JavaEmbedUtils;
import java.util.ArrayList;
public class RubyFromJava {
public String fooString() {
return "foo";
}
public static void main(String[] ARGV) {
System.out.println("Started");
RubyFromJava sTest = new RubyFromJava();
System.out.println("boring: " + sTest.fooString() + "\n"); // outputs foo
/* This script subclasses the java Object class.
It is then instantiated and the foobarString method is called. */
String script =
"require 'java'\n" +
"class RSubclass1 < java.lang.Object\n" + // subclassing java.* is magic
" def foobarString\n" +
" return @returnString = toString() + 'BAR'\n" +
" end\n" +
"end\n" +
"rsubclass = RSubclass1.new\n" +
"puts rsubclass.foobarString\n";
Ruby runtime = JavaEmbedUtils.initialize(new ArrayList());
RubyRuntimeAdapter evaler = JavaEmbedUtils.newRuntimeAdapter();
evaler.eval(runtime, script); // outputs org.jruby.proxy.java.lang.Object$Proxy0@1c7f37dBAR
System.out.println("-----------------\n");
/* This script subclasses the RubyFromJava class.
It is then instantiated and the foobarString method is called. */
script =
"require 'java'\n" +
"class RSubclass2 < Java::RubyFromJava\n" + // subclassing non {org,com}.* classpath requires you prefix the class with Java:: or java.
" def foobarString\n" +
" return @returnString = fooString() + 'BAR'\n" +
" end\n" +
"\n" +
"rsubclass = RSubclass2.new\n" +
"puts(rsubclass.foobarString())\n" +
"end";
evaler.eval(runtime, script); // outputs fooBAR
}
}
将其保存为RubyFromJava.java
,我将两者都RubyFromJava.java
保存jruby-complete-9.0.0.0.rc1.jar
在同一个目录中并运行:
rorra:~ > javac -cp ./jruby-complete-9.0.0.0.rc1.jar RubyFromJava.java
Note: RubyFromJava.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
rorra:~ > java -cp ./jruby-complete-9.0.0.0.rc1.jar:. RubyFromJava
Started
boring: foo
org.jruby.proxy.java.lang.Object$Proxy1@273e5037BAR
-----------------
fooBAR
按预期工作并从java调用jruby代码
如果您的想法是从 Ruby 调用 Java,那很容易,您可以关注位于此处的 wiki