1

Do we have a replacement of these kind of statement in java ?

#ifdef MacOSX
    #import <Cocoa/Cocoa.h>
#else
    #import <Foundation/Foundation.h>
#endif

I want to compile my java classes depending upon the conditions?

  • 3
    *"Do we have a replacement of these kind of statement in java ?"* Yeah, I call it 'Java' and it is cross-platform, negating the need to conditionally import anything. – Andrew Thompson Nov 27 '13 at 10:03

2 Answers2

8

No, Java doesn't have anything like that. While the compiler can strip out code which is guaranteed not to be executed, it's still got to be valid code. So you can have:

private static final FOO_ENABLED = false;

...

if (FOO_ENABLED) {
    System.out.println("This won't be included in the bytecode");
}

... you can't have:

private static final FOO_ENABLED = false;

...

if (FOO_ENABLED) {
    This isn't even valid code. With a real preprocessor it wouldn't matter.
}

You can run "not quite Java" code through a regular preprocessor in order to get valid Java afterwards, but that will be painful when developing.

It's better to abstract out the functionality you're interested in into interfaces / abstract classes, and then have different concrete implementations for different platforms, picking the right one at execution time.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 3
    Well... [kinda](http://stackoverflow.com/a/1813873/474189), although not in a way that lets you fiddle import statements. – Duncan Jones Nov 27 '13 at 10:01
  • @Duncan: Nor in a way which lets you have code which will only compile under certain conditions. See my edit. – Jon Skeet Nov 27 '13 at 10:03
  • Your last paragraph is the golden one. Java solves this general issue more elegantly than an `#ifdef` ever would. – Duncan Jones Nov 27 '13 at 10:05
1

No. In general you'll want to use a common superinterface for the functionality that you'd want to provide by Cocoa/Foundation, and then have two different implementing classes for that interface, depending on the platform you're targetting.

creichen
  • 1,728
  • 9
  • 16