gpt4 book ai didi

java - -Djava.library.path=... 是否等同于 System.setProperty ("java.library.path", ...)

转载 作者:IT老高 更新时间:2023-10-28 20:32:57 26 4
gpt4 key购买 nike

我加载了一个放在 ./lib 中的外部库。这两个解决方案是否设置 java.library.path 等效?

  1. 执行jar时在控制台设置路径:

    java -Djava.library.path=./lib -jar myApplication.jar
  2. 在加载库之前在代码中设置路径:

    System.setProperty("java.library.path", "./lib");

如果它们是等价的,为什么在第二个解决方案中Java 找不到库而第一个解决方案可以?

如果不是,有没有办法在代码中设置路径?

最佳答案

虽然没有很好的文档记录,但 java.library.path 系统属性就 System.loadLibrary() 方法而言是“只读”属性被关注到。这是 reported bug但它被 Sun 关闭而不是修复。问题是 JVM 的 ClassLoader 在启动时读取该属性一次,然后将其缓存,不允许我们之后以编程方式更改它。 System.setProperty("java.library.path", anyVal); 行除了 System.getProperty() 方法调用之外没有任何作用。

幸运的是,有人 posted a workaround on the Sun forums .不幸的是,该链接不再有效,但我确实找到了 the code on another source .这是您可以用来解决无法设置 java.library.path 系统属性的代码:

public static void addDir(String s) throws IOException {
try {
// This enables the java.library.path to be modified at runtime
// From a Sun engineer at http://forums.sun.com/thread.jspa?threadID=707176
//
Field field = ClassLoader.class.getDeclaredField("usr_paths");
field.setAccessible(true);
String[] paths = (String[])field.get(null);
for (int i = 0; i < paths.length; i++) {
if (s.equals(paths[i])) {
return;
}
}
String[] tmp = new String[paths.length+1];
System.arraycopy(paths,0,tmp,0,paths.length);
tmp[paths.length] = s;
field.set(null,tmp);
System.setProperty("java.library.path", System.getProperty("java.library.path") + File.pathSeparator + s);
} catch (IllegalAccessException e) {
throw new IOException("Failed to get permissions to set library path");
} catch (NoSuchFieldException e) {
throw new IOException("Failed to get field handle to set library path");
}
}

警告:这可能不适用于所有平台和/或 JVM。

关于java - -Djava.library.path=... 是否等同于 System.setProperty ("java.library.path", ...),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5419039/

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