Search code examples
javajnaunsatisfiedlinkerror

Java JNA Different implementation according to OS


I have to use Java JNA to link a C library. This library has a Windows implementation and a Linux one. These differ one from other for a single method because this method is implemented only by Windows version.

MyJnaInterface INSTANCE = (MyJnaInterface) Native.loadLibrary("MyLibrary",
                MyJnaInterface.class);

I would like to have just one version of my Java application, this may have a single interface with 2 implementation, one for windows os and one for linux os, obviously the linux implementation will have an empty method.

public interface MyJnaInterface
public class MyJnaWinImpl implements MyJnaInterface
public class MyJnaLinuxImpl implements MyJnaInterface

This works in windows, in linux OS at service startup JNA tries to find its native methods also in windows classes (also if this class is not used in runtime) and so it throws a UnsatifiedLinkError. How to solve this deadlock? I really cannot change the native library (it would be so simple...)


Solution

  • I solved using static{} block.

    public interface MyJnaInterface;
    public interface MyJnaInterfaceWin implements MyJnaInterface; // this has the WinMethod method
    
    ...
    
        private static MyJnaInterface INSTANCE;
    
        static{
            if(SystemUtils.IS_OS_LINUX){
                INSTANCE=(MyJnaInterface) Native.loadLibrary("MyLibrary",MyJnaInterface.class);
            }else{
                INSTANCE=(MyJnaInterfaceWin) Native.loadLibrary("MyLibrary",MyJnaInterfaceWin.class);
            }
        }
    
    
    ...
    
    public static void WinMethod(){
                if(!SystemUtils.IS_OS_LINUX) ((MyJnaInterfaceWin)INSTANCE).WinMethod());
            }