2

I would like to support Java 1.5+ in my application, but selectively enable features if the user is running on a Java 1.6+ JVM, using Java 1.6+-specific API calls. So I need a way to check the current version of the JVM and ensure that only available APIs are used. Of course, I'll be compiling with -target 1.5.

I've come up with:

if (System.getProperty("java.vm.version").startsWith("1.5")) {
    // Do 1.5 things
} else {
    // Do 1.6+ things
}

It seems to fit the bill, but I'm wondering if there's a "better" way?

Furthermore, if I'm careful not to call any 1.6 API calls from my 1.5 code, is there still a possibility that I will get NoSuchMethodErrors, NoClassDefFounds when running on a 1.5 JVM?

Jonathan
  • 7,536
  • 4
  • 30
  • 44
  • Possible duplicate for: http://stackoverflow.com/questions/2591083/getting-version-of-java-in-runtime – Thomas Feb 23 '12 at 19:45

1 Answers1

3

You could use reflection to see if the things you want to do exist:

try {
    DesiredClass.class.getMethod("desiredMethod", <parameter types...>)
    // Do 1.6 things
}
catch (NoSuchMethodException e) {
    // Do 1.5 things
}
parkovski
  • 1,503
  • 10
  • 13