Search code examples
javaplatform

Platform dependent code for several platforms in Java


I'm writing program that should run on both Linux and Windows OS.

if (isLinux) {
    // some linux code
} else {
    // some windows code
}

It uses platform dependent code and libraries, so it doesn't compile on Linux right now. How can I compile only part of the current OS code?


Solution

  • Create an interface:

    interface OSSpecificStuff {
        void method(...)
    

    then create two implementations of the interface, one for Windows and one for Linux.

    class LinuxStuff implements OSSpecificStuff {
        void method(...) {
            Linux specific implementation
    

    same for class WindowsStuff etc. To avoid compilation errors, compile these O/S specific classes into separate jar files.

    Create the appropriate class using:

    Class clazz = isLinux ? Class.forName("LinuxStuff") : Class.forName("WindowsStuff");
    OSSpecificStuff stuff= (OSSpecificStuff ) clazz.newInstance();
    

    Or you can just create two classes called OSSpecificStuff and put them in two different jar files and include the appropriate jar file in the classpath when you run the program.

    Advanced stuff:

    You will find a lot of posts of SE on how Class.newInstance is bad and you might want to use Constructor instead.

    Also, I haven't used generics in the above code to keep it simple.

    See Why is Class.newInstance() “evil”?