RubyHelp.java:
public class RubyHelper {
static {
System.setProperty("jruby.home", new File("").getAbsolutePath());
}
private RubyHelper() {
}
public static Object create(String className, Class interfaceClazz, String scriptFileName) {
InputStream scriptInputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(scriptFileName);
if (null == scriptInputStream) {
throw new RuntimeException("Could not find " + scriptFileName);
}
StringBuilder sb = new StringBuilder();
byte[] buf = new byte[8192];
try {
for (int n; (n = scriptInputStream.read(buf)) != -1;) {
sb.append(new String(buf, 0, n, "UTF-8"));
}
scriptInputStream.close();
} catch (IOException e) {
throw new RuntimeException("Error loading " + scriptFileName + ": " + e.getMessage());
}
Ruby runtime = JavaEmbedUtils.initialize(new ArrayList());
runtime.eval(runtime.parse(sb.toString(), scriptFileName, runtime.getCurrentContext().getCurrentScope(), 0, false));
return JavaEmbedUtils.rubyToJava(runtime, runtime.evalScriptlet(className + ".new"), interfaceClazz);
}
}
HelloService.java:
public interface HelloService {
void hello();
}
hello.rb:
class Hello
def hello
puts 'hello there'
end
end
Test.java:
public class Test {
public static void main(String[] args) throws Exception {
HelloService s = (HelloService)RubyHelper.create("Hello", HelloService.class, "hello.rb");
s.hello();
}
}
文章標籤
全站熱搜
