Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Platform dependent code for several platforms in Java

Tags:

java

platform

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?

like image 485
Andrey Putilin Avatar asked Aug 05 '26 09:08

Andrey Putilin


1 Answers

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

like image 53
rghome Avatar answered Aug 07 '26 21:08

rghome



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!