3

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?

  • Please post the relevant code. – Arnaud Feb 02 '16 at 15:50
  • JNA methods for Windows to set foreground window and "xdotool" call for Linux. When I'm complining on Linux it's of course can't find Windows JNA. But I'm also interested in solution which is not specific to my current code. – Andrey Putilin Feb 02 '16 at 15:54

1 Answers1

6

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”?

Community
  • 1
  • 1
rghome
  • 8,529
  • 8
  • 43
  • 62