<p>I maintain a Java Swing application.</p>

<p>For backwards compatibility with java 5 (for Apple machines), we maintain two codebases, 1 using features from Java 6, another without those features.</p>

<p>The code is largely the same, except for 3-4 classes that uses Java 6 features.</p>

<p>I wish to just maintain 1 codebase. Is there a way during compilation, to get the Java 5 compiler to 'ignore' some parts of my code?</p>

<p>I do not wish to simply comment/uncomment parts of my code, depending on the version of my java compiler.</p>

[{'answer_id': 74202, 'author': 'chessguy', 'author_id': 1908025, 'author_profile': 'https://Stackoverflow.com/users/1908025', 'pm_score': 2, 'selected': False, 'text': '<p>I think the best approach here is probably to use build scripts. You can have all your code in one location, and by choosing which files to include, and which not to include, you can choose what version of your code to compile. Note that this may not help if you need finer-grained control than per file.</p>\n'}, {'answer_id': 74229, 'author': 'Nikki9696', 'author_id': 456669, 'author_profile': 'https://Stackoverflow.com/users/456669', 'pm_score': 1, 'selected': False, 'text': '<p>Not really, but there are workarounds. See\n<a href="http://forums.sun.com/thread.jspa?threadID=154106&amp;messageID=447625" rel="nofollow noreferrer">http://forums.sun.com/thread.jspa?threadID=154106&amp;messageID=447625</a></p>\n\n<p>That said, you should stick with at least having one file version for Java 5 and one for Java 6, and include them via a build or make as appropriate. Sticking it all in one big file and trying to get the compiler for 5 to ignore stuff it doesn\'t understand isn\'t a good solution.</p>\n\n<p>HTH</p>\n\n<p>-- nikki --</p>\n'}, {'answer_id': 74259, 'author': 'DarenW', 'author_id': 10468, 'author_profile': 'https://Stackoverflow.com/users/10468', 'pm_score': 1, 'selected': False, 'text': '<p>This will make all the Java purists cringe (which is fun, heh heh) but i would use the C preprocessor, put #ifdefs in my source.   A makefile, rakefile, or whatever controls your build, would have to run cpp to make a temporary files to feed the compiler.  I have no idea if ant could be made to do this.  </p>\n\n<p>While stackoverflow looks like it\'ll be <em>the</em> place for all answers, you could wehn no one\'s looking mosey on over to <a href="http://www.javaranch.com" rel="nofollow noreferrer">http://www.javaranch.com</a> for Java wisdom. I imagine this question has been dealt with there, prolly a long time ago.</p>\n'}, {'answer_id': 74268, 'author': 'Burkhard', 'author_id': 12860, 'author_profile': 'https://Stackoverflow.com/users/12860', 'pm_score': 0, 'selected': False, 'text': '<p>There is no pre-compiler in Java. Thus, no way to do a #ifdef like in C.\nBuild scripts would be the best way.</p>\n'}, {'answer_id': 74292, 'author': 'freespace', 'author_id': 8297, 'author_profile': 'https://Stackoverflow.com/users/8297', 'pm_score': 0, 'selected': False, 'text': "<p>You can get conditional compile, but not very nicely - javac will ignore unreachable code. Thus if you structured your code properly, you can get the compiler to ignore parts of your code. To use this properly, you would also need to pass the correct arguments to javac so it doesn't report unreachable code as errors, and refuse to compile :-)</p>\n"}, {'answer_id': 74319, 'author': 'Jesse Glick', 'author_id': 12916, 'author_profile': 'https://Stackoverflow.com/users/12916', 'pm_score': 2, 'selected': False, 'text': '<p>Keep one "master" source root that builds under JDK 5. Add a second parallel source root that has to build under JDK 6 or higher. (There should be no overlap, i.e. no classes present in both.) Use an interface to define the entry point between the two, and a tiny bit of reflection.</p>\n\n<p>For example:</p>\n\n<pre><code>---%&lt;--- main/RandomClass.java\n// ...\nif (...is JDK 6+...) {\n    try {\n        JDK6Interface i = (JDK6Interface)\n            Class.forName("JDK6Impl").newInstance();\n        i.browseDesktop(...);\n    } catch (Exception x) {\n        // fall back...\n    }\n}\n---%&lt;--- main/JDK6Interface.java\npublic interface JDK6Interface {\n    void browseDesktop(URI uri);\n}\n---%&lt;--- jdk6/JDK6Impl.java\npublic class JDK6Impl implements JDK6Interface {\n    public void browseDesktop(URI uri) {\n        java.awt.Desktop.getDesktop().browse(uri);\n    }\n}\n---%&lt;---\n</code></pre>\n\n<p>You could configure these as separate projects in an IDE using different JDKs, etc. The point is that the main root can be compiled independently and it is very clear what you can use in which root, whereas if you try to compile different parts of a single root separately it is too easy to accidentally "leak" usage of JDK 6 into the wrong files.</p>\n\n<p>Rather than using Class.forName like this, you can also use some kind of service registration system - java.util.ServiceLoader (if main could use JDK 6 and you wanted optional support for JDK 7!), NetBeans Lookup, Spring, etc. etc.</p>\n\n<p>The same technique can be used to create support for an optional library rather than a newer JDK.</p>\n'}, {'answer_id': 74366, 'author': 'Steve g', 'author_id': 12092, 'author_profile': 'https://Stackoverflow.com/users/12092', 'pm_score': 2, 'selected': False, 'text': '<p>You can probably refactor your code so that conditional compile really isn\'t needed, just conditional classloading.  Something like this:</p>\n\n<pre><code>public interface Opener{\n\npublic void open(File f);\n\n public static class Util{\n        public Opener getOpener(){\n          if(System.getProperty("java.version").beginsWith("1.5")){\n           return new Java5Opener();\n          }\n          try{ \n            return new Java6Opener();\n           }catch(Throwable t){\n            return new Java5Opener();\n           }\n        }\n }\n\n}\n</code></pre>\n\n<p>This could be a lot of effort depending on how many version-specific pieces of code you have.</p>\n'}, {'answer_id': 74555, 'author': '18Rabbit', 'author_id': 12662, 'author_profile': 'https://Stackoverflow.com/users/12662', 'pm_score': 3, 'selected': True, 'text': '<p>Assuming that the classes have similar functionality with 1.5 vs. 6.0 differences in implementation you could merge them into one class.  Then, without editing the source to comment/uncomment, you can rely on the optimization that the compiler always do. If an if expression is always false, the code in the if statement will not be included in the compilation.</p>\n\n<p>You can make a static variable in one of your classes to determine which version you want to run:</p>\n\n<pre><code>public static final boolean COMPILED_IN_JAVA_6 = false;\n</code></pre>\n\n<p>And then have the affected classes check that static variable and put the different sections of code in a simple if statement</p>\n\n<pre><code>if (VersionUtil.COMPILED_IN_JAVA_6) {\n  // Java 6 stuff goes here\n} else {\n  // Java 1.5 stuff goes here\n}\n</code></pre>\n\n<p>Then when you want to compile the other version you just have to change that one variable and recompile.  It might make the java file larger but it will consolidate your code and eliminate any code duplication that you have.  Your editor may complain about unreachable code or whatever but the compiler should blissfully ignore it.</p>\n'}, {'answer_id': 74603, 'author': 'Bill K', 'author_id': 12943, 'author_profile': 'https://Stackoverflow.com/users/12943', 'pm_score': 0, 'selected': False, 'text': "<p>The public static final solution mentioned above has one additional benefit the author didn't mention--as I understand it, the compiler will recognize it at compile time and compile out any code that is within an if statement that refers to that final variable.</p>\n\n<p>So I think that's the exact solution you were looking for.</p>\n"}, {'answer_id': 74617, 'author': 'Garth Gilmour', 'author_id': 2635682, 'author_profile': 'https://Stackoverflow.com/users/2635682', 'pm_score': 0, 'selected': False, 'text': "<p>A simple solution could be:</p>\n\n<ul>\n<li>Place the divergent classes outside of your normal classpath.</li>\n<li>Write a simple custom classloader and install it in main as your default.</li>\n<li>For all classes apart from the 5/6 ones the cassloader can defer to its parent (the normal system classloader)</li>\n<li>For the 5/6 ones (which should be the only ones that cannot be found by the parent) it can decide which to use via the 'os.name' property or one of your own.</li>\n</ul>\n"}, {'answer_id': 76114, 'author': 'Michael Myers', 'author_id': 13531, 'author_profile': 'https://Stackoverflow.com/users/13531', 'pm_score': 1, 'selected': False, 'text': '<p>It depends on what Java 6 features you want to use. For a simple thing like adding row sorters to JTables, you can actually test at runtime:</p>\n\n<pre><code>private static final double javaVersion =\n         Double.parseDouble(System.getProperty("java.version").substring(0, 3));\nprivate static final boolean supportsRowSorter =\n         (javaVersion &gt;= 1.6);\n\n//...\n\nif (supportsRowSorter) {\n    myTable.setAutoCreateRowSorter(true);\n} else {\n    // not supported\n}\n</code></pre>\n\n<p>This code must be compiled with Java 6, but can be run with any version (no new classes are referenced).</p>\n\n<p>EDIT: to be more correct, it will work with any version since 1.3 (according to <a href="http://java.sun.com/j2se/versioning_naming.html" rel="nofollow noreferrer" title="J2SE SDK/JRE Version String Naming Convention">this page</a>).</p>\n'}, {'answer_id': 76276, 'author': 'Ian', 'author_id': 4396, 'author_profile': 'https://Stackoverflow.com/users/4396', 'pm_score': 3, 'selected': False, 'text': '<p>The suggestions about using custom class loaders and dynamically commented code are a bit incredulous when it comes to maintenance and the preservation of the sanity of whichever poor soul picks up the project after you shuffle to pastures new.</p>\n\n<p>The solution is easy.  Pull the affected classes out into two separate, independent projects - make sure the package names are the same, and just compile into jars that you can then consume in your main project.  If you keep the package names the same, and the method signatures the same, no problems - just drop whichever version of the jar you need into your deployment script.  I would assume you run separate build scripts or have separate targets in the same script - ant and maven can both easily handle conditionally grabbing files and copying them.</p>\n'}, {'answer_id': 76951, 'author': 'shadit', 'author_id': 9925, 'author_profile': 'https://Stackoverflow.com/users/9925', 'pm_score': 1, 'selected': False, 'text': '<p>You can do all of your compiling exclusively on Java6 and then use System.getProperty("java.version") to conditionally run either the Java5 or the Java6 code path.</p>\n\n<p>You can have Java6-only code in a class and the class will run fine on Java5 as long as the Java6-only code path is not executed.</p>\n\n<p>This is a trick that is used to write applets that will run on the ancient MSJVM all the way up to brand-new Java Plug-in JVMs.</p>\n'}, {'answer_id': 146035, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>You can use reflection API. put all your 1.5 code in one class and 1.6 api in another. In your ant script create two targets one for 1.5 that won't compile the 1.6 class and one for 1.6 that won't compile the class for 1.5. in your code check your java version and load the appropriate class using reflection that way javac won't complain about missing functions. This is how i can compile my MRJ(Mac Runtime for Java) applications on windows.</p>\n"}]
['https://Stackoverflow.com/questions/74171', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12944/']