在Java中在运行时为本机库添加新路径 [英] Adding new paths for native libraries at runtime in Java

查看:128
本文介绍了在Java中在运行时为本机库添加新路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在运行时为本机库添加新路径?
(而不是使用属性java.library.path启动Java),因此在尝试查找时,对 System.loadLibrary(nativeLibraryName)的调用将包含该路径 nativeLibraryName
这是可能的,或者这些路径在JVM启动后被冻结了吗?

Is it possible to add a new path for native libraries at runtime ?. (Instead of starting Java with the property java.library.path), so a call to System.loadLibrary(nativeLibraryName) will include that path when trying to find nativeLibraryName. Is that possible or these paths are frozen once the JVM has started ?

推荐答案

没有少量黑客行为似乎是不可能的即访问ClassLoader类的私有字段)

It seems impossible without little hacking (i.e. accessing private fields of the ClassLoader class)

博客提供了两种方法。

记录中,这是简短版本。

For the record, here is the short version.

选项1:使用新值完全替换java.library.path)

Option 1: fully replace java.library.path with the new value)

public static void setLibraryPath(String path) throws Exception {
    System.setProperty("java.library.path", path);

    //set sys_paths to null so that java.library.path will be reevalueted next time it is needed
    final Field sysPathsField = ClassLoader.class.getDeclaredField("sys_paths");
    sysPathsField.setAccessible(true);
    sysPathsField.set(null, null);
}

选项2:添加新路径当前java.library.path

Option 2: add a new path to the current java.library.path

/**
* Adds the specified path to the java library path
*
* @param pathToAdd the path to add
* @throws Exception
*/
public static void addLibraryPath(String pathToAdd) throws Exception{
    final Field usrPathsField = ClassLoader.class.getDeclaredField("usr_paths");
    usrPathsField.setAccessible(true);

    //get array of paths
    final String[] paths = (String[])usrPathsField.get(null);

    //check if the path to add is already present
    for(String path : paths) {
        if(path.equals(pathToAdd)) {
            return;
        }
    }

    //add the new path
    final String[] newPaths = Arrays.copyOf(paths, paths.length + 1);
    newPaths[newPaths.length-1] = pathToAdd;
    usrPathsField.set(null, newPaths);
}

这篇关于在Java中在运行时为本机库添加新路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆