我有这个红宝石课程:
require 'stringio'
require 'hirb'
class Engine
def initialize()
@binding = Kernel.binding
end
def run(code)
# run something
stdout_id = $stdout.to_i
$stdout = StringIO.new
cmd = <<-EOF
$SAFE = 3
$stdout = StringIO.new
begin
#{code}
end
EOF
begin
result = Thread.new { Kernel.eval(cmd, @binding) }.value
rescue SecurityError
return "illegal"
rescue Exception => e
return e
ensure
output = get_stdout
$stdout = IO.new(stdout_id)
end
return output
end
private
def get_stdout
raise TypeError, "$stdout is a #{$stdout.class}" unless $stdout.is_a? StringIO
$stdout.rewind
$stdout.read
end
end
“运行”方法应该调用 IRB 的函数并捕获输出(字符串格式)。我想从 Java 类调用此函数,但它找不到 IRB 方法,即使它们已加载(需要“hirb”)。我的 java 类看起来像这样:
public class MyClass {
private final static String jrubyhome = "/usr/lib/jruby/";
private String rubySources;
private String hirbSource;
private String myEngine;
private boolean loaded = false;
private void loadPaths() {
String userDir;
userDir = System.getProperty("user.dir");
rubySources = userDir + "/../ruby";
hirbSource = userDir + "/hirb.rb";
myEngine = rubySources + "/engine.rb";
System.setProperty("jruby.home", jrubyhome);
System.setProperty("org.jruby.embed.class.path", rubySources+":"+hirbSource);
System.setProperty("hbase.ruby.sources", rubySources+":"+hirbSource);
}
private String commandResponse(String command)
throws FileNotFoundException
{
String response;
loadPaths();
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("jruby");
ScriptingContainer container = new ScriptingContainer();
Reader reader = new FileReader(myEngine);
try {
Object receiver = engine.eval(reader);
String method = "run";
Object ob = container.callMethod(receiver,method,command);
response = ob.getClass().toString();
return response;
} catch (ScriptException e) {
System.out.println("exception");
}
return "FAILED";
}
public static void main(String args[])
throws IOException {
MyClass my = new MyClass();
System.out.println(my.commandResponse(args[0]));
}
}
你知道可能是什么问题吗?
[编辑]在我扩展内核模块并添加它工作的命令之后。