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?
I've built on top of jitter's solution. This allows you to find out who (ClassLoader, Class) loaded each native library.
import java.lang.reflect.Field;
import java.util.*;
import java.util.Map.Entry;
/**
* Helper functions for native libraries.
*
* @author Gili Tzabari
*/
public class NativeLibraries
{
private final Field loadedLibraryNames;
private final Field systemNativeLibraries;
private final Field nativeLibraries;
private final Field nativeLibraryFromClass;
private final Field nativeLibraryName;
/**
* Creates a new NativeLibraries.
*
* @throws NoSuchFieldException if one of ClassLoader's fields cannot be found
*/
public NativeLibraries() throws NoSuchFieldException
{
this.loadedLibraryNames = ClassLoader.class.getDeclaredField("loadedLibraryNames");
loadedLibraryNames.setAccessible(true);
this.systemNativeLibraries = ClassLoader.class.getDeclaredField("systemNativeLibraries");
systemNativeLibraries.setAccessible(true);
this.nativeLibraries = ClassLoader.class.getDeclaredField("nativeLibraries");
nativeLibraries.setAccessible(true);
Class> nativeLibrary = null;
for (Class> nested : ClassLoader.class.getDeclaredClasses())
{
if (nested.getSimpleName().equals("NativeLibrary"))
{
nativeLibrary = nested;
break;
}
}
this.nativeLibraryFromClass = nativeLibrary.getDeclaredField("fromClass");
nativeLibraryFromClass.setAccessible(true);
this.nativeLibraryName = nativeLibrary.getDeclaredField("name");
nativeLibraryName.setAccessible(true);
}
/**
* Returns the names of native libraries loaded across all class loaders.
*
* @return a list of native libraries loaded
*/
public List getLoadedLibraries()
{
try
{
@SuppressWarnings("UseOfObsoleteCollectionType")
final Vector result = (Vector) loadedLibraryNames.get(null);
return result;
}
catch (IllegalArgumentException | IllegalAccessException e)
{
throw new AssertionError(e);
}
}
/**
* Returns the native libraries loaded by the system class loader.
*
* @return a Map from the names of native libraries to the classes that loaded them
*/
public Map> getSystemNativeLibraries()
{
try
{
Map> result = new HashMap<>();
@SuppressWarnings("UseOfObsoleteCollectionType")
final Vector