gpt4 book ai didi

java - 如何动态加载 AttachProvider (attach.dll)

转载 作者:搜寻专家 更新时间:2023-10-31 19:57:08 24 4
gpt4 key购买 nike

我正在使用 jdk 的 tools.jar 中的 com.sun.tools.attach,它需要指定的 java.library.path启动时指向 attach.dll 的 env 以正确实例化提供程序,例如 WindowsAttachProvider。由于某些原因,我需要动态加载捆绑的 attach.dll 之一。我尝试使用这样的一些:

public static void main(String[] args) throws Exception {
Path bin = Paths.get(System.getProperty("user.dir"),"bin").toAbsolutePath();
switch (System.getProperty("os.arch")) {
case "amd64":
bin = bin.resolve("win64");
break;
default:
bin = bin.resolve("win32");
}
// Dynamic setting of java.library.path only seems not sufficient
System.setProperty("java.library.path", System.getProperty("java.library.path") + File.pathSeparator + bin.toString());
// So I try to manual loading attach.dll. This is not sufficient too.
System.load(bin.resolve("attach.dll").toString());
// I'm using com.sun.tools.attach in my app
new myApp();
}

如果我用 jdk(在普通 jre 中)运行它,它会向我报告:

java.util.ServiceConfigurationError: com.sun.tools.attach.spi.AttachProvider:
Provider sun.tools.attach.WindowsAttachProvider could not be instantiated:
java.lang.UnsatisfiedLinkError: no attach in java.library.path
Exception in thread "main" com.sun.tools.attach.AttachNotSupportedException:
no providers installed
at com.sun.tools.attach.VirtualMachine.attach(...

如何在启动时不指定 -Djava.library.path 指向 attach.dll 来安装 attach provider?

最佳答案

您正在使用的 API 正在使用 loadLibrary(String) .您似乎无法通过调用更明确的 load(String) 来成功抢占(使其成功)首先。

所以你必须在java.library.path中指定路径。

该系统属性在 JVM 生命周期的早期设置一次,并且不能通过标准方式修改。

因此传统的解决方案是在启动 JVM 时传递适当的 java.library.path

或者,您可以研究黑客以在 JVM 启动后使用反射更改此属性。我没有尝试过这些。

例如,参见 here :

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

Field fieldSysPath = ClassLoader.class.getDeclaredField( "sys_paths" );
fieldSysPath.setAccessible( true );
fieldSysPath.set( null, null );

顺便说一句,我建议将您的自定义路径添加到现有路径,而不是替换它。

关于java - 如何动态加载 AttachProvider (attach.dll),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11134159/

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