Java – Handling different API versions in same Java source


I'm sure this is a dumb question, but.. We have the same Java source files and we want to use a different version of a Java API (jar file) depending on the client we are building our app for.

The newer version of the API has the methods setAAA() and setBBB() which we reference in our Java source:

if (...) {

This code will fail if compiled with the old API has the old API doesn't have these setters. Is there any way to conditionalize this code to only compile the setter lines if we are using the new API?


Best Solution

Java really wasn't meant for this conditional compilation (unlike C++), and it honestly sounds like a recipe for ending up in "classpath hell".

While you could manually start dealing with functions that return the version of your API, you then have a classfile that fits a specific version, but with no indications that it may be incompatible.

I've encountered this situation before (e.g., working with different versions of Eclipse) and it's not pretty. What I ended up doing is having an interface with two different implementations, one for each API, put each of them in a separate project (a plug-in in my case), and then tried to load them with a factory or an injection. Isolate them as well as you can.