gpt4 book ai didi

jruby - 如何将 Jruby proc/block/closure 返回给 java 并调用它

转载 作者:行者123 更新时间:2023-12-01 05:39:03 24 4
gpt4 key购买 nike

我希望能够将 block 从嵌入式 jruby 实例返回到常规 java。我的 java 代码应该能够传递所需的参数(假设它知道正确的参数)然后接收结果。任何 sample 将不胜感激。

最佳答案

如果您可以直接嵌入,请使用 JavaEmbedUtils 并在定义您的 proc/block/closure 的 ruby​​ 代码字符串上调用 eval,或者让您的 ruby​​ 代码实现一个接口(interface),其中某些方法返回您的 proc/block/closure。令人难以置信的人为示例将以下两个数字相加:

SampleApp.java

import org.jruby.Ruby;
import org.jruby.RubyRuntimeAdapter;
import org.jruby.RubyFixnum;
import org.jruby.RubyProc;
import org.jruby.javasupport.JavaEmbedUtils;
import org.jruby.runtime.Block;
import org.jruby.runtime.ThreadContext;
import java.util.ArrayList;

class SampleApp {
public static void main(String[] args) {

// Create runtime instance
Ruby runtime = JavaEmbedUtils.initialize(new ArrayList());

// Parameters
RubyFixnum paramA = new RubyFixnum(runtime, 1);
RubyFixnum paramB = new RubyFixnum(runtime, 2);

// Runtime eval method
RubyRuntimeAdapter evaler = JavaEmbedUtils.newRuntimeAdapter();
RubyProc additionProcFromEval = (RubyProc)evaler.eval(runtime, "Proc.new { |a, b| a + b }");
printProcResult(runtime, additionProcFromEval, paramA, paramB);

// Interface implementation method
SomeInterfaceImpl someImpl = new SomeInterfaceImpl();
RubyProc additionProcFromInterface = (RubyProc)someImpl.getAdditionProc();
printProcResult(runtime, additionProcFromInterface, paramA, paramB);

// Shutdown and terminate instance
JavaEmbedUtils.terminate(runtime);
}

protected static void printProcResult(Ruby runtime, RubyProc proc, RubyFixnum paramA, RubyFixnum paramB) {
Block block = proc.getBlock();
ThreadContext threadContext = ThreadContext.newContext(runtime);
int result = (Integer)block.call(threadContext, paramA, paramB).toJava(new Integer(0).getClass());
System.out.println("Result = " + result);
}
}

SomeInterface.java

interface SomeInterface {
org.jruby.RubyProc getAdditionProc();
}

SomeInterfaceImpl.rb

require 'java'
class SomeInterfaceImpl

include Java::SomeInterface

java_signature 'org.jruby.RubyProc getAdditionProc()'
def getAdditionProc()
return Proc.new { |a, b| a + b }
end

end

这就是您可以测试的方式:

javac -classpath jruby.jar SomeInterface.java
jrubyc --javac -cp . SomeInterfaceImpl.rb
javac -cp jruby.jar:. SampleApp.java
java -cp jruby.jar:. SampleApp

引用:

https://github.com/jruby/jruby/wiki/DirectJRubyEmbedding

http://tommy.chheng.com/2010/06/20/call-a-jruby-method-from-java/

关于jruby - 如何将 Jruby proc/block/closure 返回给 java 并调用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6888552/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com