本文介绍了获取JRuby jar路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与类似问题,我想知道如何获取当前jar文件的路径。但与其他问题不同,我想知道 jar 的路径,而不是jar内部当前文件的路径。例如,假设我在/Users/MyUser/Jars/foo.jar中有一个jruby jar,里面是foo.jar / java / style / class / path.class中编译的ruby文件。 class.path如何获取路径/Users/MyUser/Jars/foo.jar?

Similar to this question, I'd like to know how to get the current jar file's path. But unlike the other question, I want to know the jar's path, not the path of the current file inside the jar. For example, say I had a jruby jar at "/Users/MyUser/Jars/foo.jar" and inside was a compiled ruby file at "foo.jar/java/style/class/path.class". How could class.path get the path "/Users/MyUser/Jars/foo.jar"?

我还看到,但我只是不知道如何翻译它...

I also saw a way to do it in Java, but I just don't know how to translate it...

推荐答案

我已经尝试过这一点,任何从JRuby调用代码的尝试都会返回jruby jar本身哪种有意义,因为逻辑确实是从那个罐子里评估/执行的。例如:

I have experimented with this a bit, and any attempt to call the code from JRuby returns the jruby jar itself, which kind of makes sense as the logic is indeed evaluated/executed from that jar. For instance:

require 'java'
puts self.to_java.get_class().protection_domain().code_source().location().path()

require 'java'

class Path
  def get_jar_path
    self.to_java.get_class().protection_domain().code_source().location().path()
  end
end

puts Path.new.get_jar_path

都返回 jruby-complete.jar 的路径,这在某种程度上是有用的,但显然不是你的'重新寻找。

both return the path to jruby-complete.jar, which can be useful to some extent but apparently not what you’re looking for.

我能让这个工作的唯一方法(使用 rawr ,但这很容易如果使用 warbler ,则适用于在 src / java / org / ruby​​forge / rawr 中创建Java类:

The only way I could get this to work (with rawr, but this can be easily adapted if you use warbler) is to create a Java class in src/java/org/rubyforge/rawr:

package org.rubyforge.rawr;

public class Path {
  public String getJarPath() {
    return getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
  }
}

然后从JRuby脚本中调用此类:

Then call this class from the JRuby script:

require 'java'
java_import 'org.rubyforge.rawr.Path'

puts Path.new.get_jar_path

这篇关于获取JRuby jar路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 21:44