What I mean is this: I have written a very elaborate Java code that is aimed for Android devices. Hence, it includes several definitions that are only available in Android (such as using the TTS-STT engine). However, the majority of the code can easily work also on desktop.
For now, to do so, I have to cross out Android related methods and compile it for desktop. However, as I often update the original code for Android, it is kind of exhausting to keep doing the same editing for the desktop.
Is there a way I can tell the program to worry about a certain part of the code only if the running OS is Android? Or OSX, Windows, etc. So that it will compile without errors no matter the OS and then selectively run certain methods?
Thank you very much, have a nice day
Asked
Active
Viewed 79 times
2
-
1For selectively *running* depending on the OS, check out System Properties, for instance try `System.out.println(System.getProperty("os.name"));` https://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html – Arjan Jun 10 '16 at 01:28
-
1@Arjan this doesn't solve the OP's problem - the code still won't compile on desktop if he is referencing android native methods. As I understand it, he wants to be able to compile and use a single codebase regardless of the OS he is running on. – nhouser9 Jun 10 '16 at 01:33
-
@nhouser9 It does indeed not solve any compilation problems. – Arjan Jun 10 '16 at 02:18
-
1A solution would be to split the code, one library with most of the stuff, an Android project and a desktop project which use the library. – Arjan Jun 10 '16 at 02:21
-
@Arjan Thanks that sounds like a good idea. I just thought maybe there could be something in Java like "#ifdef __APPLE__ " from C++. – Jun 10 '16 at 14:47
-
#ifdef is a compile time option and is used because the target system is known when the code is compiled. Java doesn't know what the target is when it is compiled. So by checking the value of System.getProperty("os.name") against the known list of names for operating systems and versions, you can create if blocks that are just as flexible as the #ifdef blocks. – Bradley Ross Jul 15 '21 at 02:44
1 Answers
0
See SWT jar for different platform
SWT has a similar situation in that it uses different code for the different platforms. I would suggest that you look at the reference above. One of the suggestions in the post was that you load part of the code using implementing classes by name as is commonly done in JDBC.
If you use something like Git, you can have the versions for the different operating systems on different branches. I would also go for the approach mentioned by Arjan where the operating system specific code could be restricted as much as possible.

Community
- 1
- 1

Bradley Ross
- 445
- 2
- 8
-
Thank you! I will see this and come back here to comment my progress for future reference (if I can indeed have some progress XD) – Jun 10 '16 at 14:49