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

kbe*_*bec 5 java dll

我正在使用com.sun.tools.attachjdk tools.jar,它需要一个指定的java.library.pathenv指向attach.dll启动时正确实例化提供程序,如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();
}
Run Code Online (Sandbox Code Playgroud)

如果我用jdk(在normall 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(...
Run Code Online (Sandbox Code Playgroud)

如何安装附加提供程序而不指定启动时-Djava.library.path指向attach.dll

sud*_*ode 6

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

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

该System属性在JVM生命周期的早期设置,并且不能通过标准方法进行修改.

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

或者,您可以查看hack以在使用反射启动JVM后更改此属性.我还没有尝试过这些.

例如,请看这里:

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

Field fieldSysPath = ClassLoader.class.getDeclaredField( "sys_paths" );
fieldSysPath.setAccessible( true );
fieldSysPath.set( null, null );
Run Code Online (Sandbox Code Playgroud)

顺便说一句,我建议您预先挂起现有路径的自定义路径,而不是替换它.