Java: easiest way to package both Java 1.5 and 1.6 code

Posted by WizardOfOdds on Stack Overflow See other posts from Stack Overflow or by WizardOfOdds
Published on 2010-03-15T16:11:56Z Indexed on 2010/03/15 16:19 UTC
Read the original article Hit count: 311

Filed under:
|
|
|

I want to package a piece of code that absolutely must run on Java 1.5. There's one part of the code where the program can be "enhanced" if the VM is an 1.6 VM.

Basically it's this method:

 private long[] findDeadlockedThreads() {
    // JDK 1.5 only supports the findMonitorDeadlockedThreads()
    // method, so you need to comment out the following three lines
    if (mbean.isSynchronizerUsageSupported())
      return mbean.findDeadlockedThreads();
    else
      return mbean.findMonitorDeadlockedThreads();
  }

What would be easiest way to have this compile on 1.5 and yet do the 1.6 method calls when on 1.6 ?

In the past I've done something similar by compiling a unique 1.6 class that I would package with my app and instantiate using a ClassLoader when on 1.6 (because an 1.6 JVM is perfectly fine mixing 0x32 and 0x31 classes), but I think it's a bit overkill (and a bit painful because during the build process you have to build both 0x31 and 0x32 .class files).

How should I go if I wanted to compile the above method on 1.5? Maybe using reflection but then how (I'm not familiar at all with reflection)

Note: if you're curious, the above method comes from this article: http://www.javaspecialists.eu/archive/Issue130.html

(but I don't want to "comment the three lines" like in the article, I want this to compile and run on both 1.5 and 1.6)

© Stack Overflow or respective owner

Related posts about java

Related posts about java1.5