Archive for August 2009

Sometimes you just have to try it

I was racking my brains out, trying to solve what seems to be a normal problem in Java, at least for swing/application developers.

How do I use new features in JDK 6 that are not available in JDK 5 but still have my application run when using a Java 5 runtime and also that everything will run seamlessly in Intellij? In particular, I’m referring to the JDK6 Desktop API for email, printing, browsing, …

I was fomenting all kinds of horrific scenarios, from conditional compilation, to manipulating the class loader to dynamically compiled code, all of them being rather distasteful.

In reality, the solution is so much simpler. I decided to just do it.

  1. Encapsulate the Desktop API in a wrapper class, called Desktop it exposes the needed functionality like email, browser, printing
  2. Compile with JDK 1.5 and Java 1.5 source flags.
  3. I ran it to see what would happen with Java 5
  4. The epiphany! NoClassDefinitionFound error, which can be simply caught and the set the desktop class to null.

Doing the above is kind of ugly and you have conditional checks for desktop == null in a few places, but is a good first start, since it worked. So how about using a factory, that works even better, the best part of using a factory is that there are no more conditional check for null in the code and also no exceptions are thrown.

Something that is easy to forget about Java is that the linking is deferred until execution. So compiling the code with JDK 1.5 as the target is no problem, since it won’t try to link the Java Desktop class, and the factory avoids the issue which I assume is a feature of the JIT, but I need to explore that a little more.