Search code examples
javaclassloader

Loading a Java class with native code dependency


I'm writing a program that loads all the classes from a specified folder.

Some of the classes are creating objects in static block and these objects in turn are making some native calls during their creation. Since I do not have the native library I'm seeing a java.lang.UnsatisfiedLinkError

Here is a example scenario.

Class A extends SuperA
{
  public static B b = new B(); 
  ...
  ...
}

Class B
{
   public B()
   {
      someNativeCall(); // Causing the LinkError
   }
}

Class.forName("A"); // Loading of Class A

I'm loading the Class A here to check some of its properties like its Super Classes etc. So I don't even care if B is created or not :) Since there can be many classes like A in a given folder, is there a generic way of making sure that loading of classes like A doesn't fail?

Update: I know that native library needs to be present and how it needs to be added. But I don't have the native library and thus am asking for this hack.


Solution

  • The .DLL or .so that implements the native function needs to be on the system path. The VM will call loadlibrary to load the relevant .dll/.so and if it's not found it will throw an UnsatisfiedLinkError.

    You can catch the UnsatisfiedLinkError to ignore the problem but you won't be able to use the classes that depend on it.

    If you want to examine the classes but not actually use them, you could use the Java Dissasembeler, javap. You may be able to access the features you need programatically - javap is defined in the package sun.tools.javap and the implementation is in $JDK\lib\tools.jar