开发者

How to use JNI, but only when available for current platform?

开发者 https://www.devze.com 2022-12-22 22:20 出处:网络
What is the common way (or best practice) to optionally use JNI? E.g. I have a Java class and this class is 100% pure Java, so it can run on all platforms. However, on some platforms I\'d like to spe

What is the common way (or best practice) to optionally use JNI?

E.g. I have a Java class and this class is 100% pure Java, so it can run on all platforms. However, on some platforms I'd like to speed up some heavy calculations using JNI - which works fine. Unfortunately I cannot support any existing Java platform in the world. So I guess it is fine to initially only support the big three: Linux, Windows, Mac OS X.

So what I'd like to do is to use JNI on those three platforms and use the 100开发者_StackOverflow% pure Java version on all other platforms. Now I can think of various ways how to do that (loading class dynamically for example and either loading the JNI class or the pure Java one), but thinking that this is a common issue that thousands of projects had to solve in the past for sure, I'm really surprised to not find any documentation or references to the question how to solve this most elegantly or effectively.


If it really makes sense to supply two different versions you could do the following:

  • Create an interface for the class
  • Implement the interface in a class in pure Java
  • Implement the interface in a class that uses JNI

Then you can write a factory method that instantiates the correct class:

public static SomeInterface getInterface()
{               
    SomeInterface res = new JavaSomeInterfaceImpl();

    if (System.getProperty("os.name").matches(".*Windows.*"))
    {
        File library = new File("mylibrary.dll");
        System.load(library.getAbsolutePath());
        res = new NativeSomeInterfaceImpl();
    }

    return res; 
}


Your platform dependant code should be in a platform dependant class ;-)

Suppose you have a main "Algorithm" class (or better, interface). This interface is implemented by a WindowsAlgorithm using JNI and a HaikuAlgorithm not doing so (it's only for the sake of example). The only thing you have to do now is to load the right one depending upon your client OS, which I think is rather mundane to do.

0

精彩评论

暂无评论...
验证码 换一张
取 消