How to influence search path of System.loadLibrary() through Java code?

前端 未结 6 1095
一向
一向 2021-02-04 03:18

In a Java project, I am using a third-party library that loads some native library via

System.loadLibrary(\"libName\");

I\'d like to be able to

6条回答
  •  旧巷少年郎
    2021-02-04 03:56

    Just recently ran into this issue and using OpenJDK where a NullPointerException is thrown (as 0-0 mentioned the Samil's answer). The following works in OpenJDK and should work with Oracle JDK as well.

    (Option 1) Replace the java.library.path

    System.setProperty("java.library.path", newPath);
    Field field = ClassLoader.class.getDeclaredField("sys_paths");
    field.setAccessible(true);
    field.set(ClassLoader.getSystemClassLoader(), new String[]{newPath});
    

    (Option 2) Add to existing java.library.path

    String libPath = System.getProperty("java.library.path");
    String newPath;
    
    if (libPath == null || libPath.isEmpty()) {
        newPath = path;
    } else {
        newPath = path + File.pathSeparator + libPath;
    }
    
    System.setProperty("java.library.path", newPath);
    
    Field field = ClassLoader.class.getDeclaredField("sys_paths");
    field.setAccessible(true);
    
    // Create override for sys_paths
    ClassLoader classLoader = ClassLoader.getSystemClassLoader(); 
    List newSysPaths = new ArrayList<>();
    newSysPaths.add(path);  
    newSysPaths.addAll(Arrays.asList((String[])field.get(classLoader)));
    
    field.set(classLoader, newSysPaths.toArray(new String[newSysPaths.size()]));
    

提交回复
热议问题