package com.demo.util;

import java.io.IOException;
import java.lang.reflect.Field;

public class DllAddUtil {

    /**
     *
     * 注意：jvm实现不是用的变量usr_paths来保存java.library.path的值，需要去查看源码修改
     * @param libraryPath
     * @throws IOException
     */
    public static void addLibraryDir(String libraryPath) throws IOException {
        try {
            Field field = ClassLoader.class.getDeclaredField("usr_paths");
            field.setAccessible(true);
            StringBuilder sb = new StringBuilder();
            String[] paths = (String[]) field.get(null);
            for (int i = 0; i < paths.length; i++) {
                if (libraryPath.equals(paths[i])) {
                    return;
                }
                sb.append(paths[i]).append(';');
            }

            sb.append(libraryPath);
            System.setProperty("java.library.path", sb.toString());
            final Field sysPathsField = ClassLoader.class.getDeclaredField("sys_paths");
            sysPathsField.setAccessible(true);
            sysPathsField.set(null, null);
        } catch (IllegalAccessException e) {
            throw new IOException(
                    "Failedto get permissions to set library path");
        } catch (NoSuchFieldException e) {
            throw new IOException(
                    "Failedto get field handle to set library path");
        }
    }
}
