如何获取已加载的 JNI 库列表?

2022-01-25 00:00:00 java java-native-interface

正如题主所说,Java 中有没有办法获取在任何给定时间已加载的所有 JNI 本机库的列表?

Just what the subject says, is there a way in Java to get a list of all the JNI native libraries which have been loaded at any given time?

推荐答案

如果你是这个意思,有一种方法可以确定所有当前加载的本地库.无法确定已卸载的库.

There is a way to determine all currently loaded native libraries if you meant that. Already unloaded libraries can't be determined.

基于 Svetlin Nakov 的工作 (将 JVM 中加载的类提取到单个 JAR) 我做了一个 POC,它为您提供了从应用程序类加载器和当前类加载器加载的本机库的名称类.

Based on the work of Svetlin Nakov (Extract classes loaded in JVM to single JAR) I did a POC which gives you the names of the loaded native libraries from the application classloader and the classloader of the current class.

第一个简化版本没有 bu....it 异常处理,漂亮的错误消息,javadoc,....

First the simplified version with no bu....it exception handling, nice error messages, javadoc, ....

通过反射获取类加载器存储已加载库的私有字段

Get the private field in which the class loader stores the already loaded libraries via reflection

public class ClassScope {
    private static final java.lang.reflect.Field LIBRARIES;
    static {
        LIBRARIES = ClassLoader.class.getDeclaredField("loadedLibraryNames");
        LIBRARIES.setAccessible(true);
    }
    public static String[] getLoadedLibraries(final ClassLoader loader) {
        final Vector<String> libraries = (Vector<String>) LIBRARIES.get(loader);
        return libraries.toArray(new String[] {});
    }
}

像这样调用上面的代码

final String[] libraries = ClassScope.getLoadedClasses(ClassLoader.getSystemClassLoader()); //MyClassName.class.getClassLoader()

瞧,libraries 保存了加载的本地库的名称.

And voilá libraries holds the names of the loaded native libraries.

从这里获取完整的源代码

相关文章