tags:

views:

833

answers:

1

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?

+3  A: 

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

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.

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[] {});
    }
}

Call the above like this

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

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

Get the full source code from here

jitter
Thanks! I tried this and got this error message: java.lang.RuntimeException: java.lang.IllegalAccessException: Class net.grow.web.ClassScope can not access a member of class java.lang.ClassLoader with modifiers "private static"
benhsu
Try adding LIBRARIES.setAccessible(true); after the call to getDeclaredField if you don't have that already. If it still fails then either your JVM is not SUN compatible or there is a SecurityManager in place which prevents you from using the reflection mechanism
jitter
A last idea (if applicable to your environment) would be to write your own ClassLoader as an Object Adapter for the normal ClassLoader. And there implement some kind of "logging" for the calls to load and loadLibrary
jitter
Great idea, just added this to our debug console.
Daniel