Writing JDK Release-Dependent Code

Problem

You need to write code that depends on the JDK release.

Solution

Don’t do this.

Discussion

Although Java is meant to be portable, there are some significant variations in Java runtimes. Sometimes you need to work around a feature that may be missing in older runtimes, but want to use it if it is present. So one of the first things you want to know is how to find out the JDK release corresponding to the Java runtime. This is easily obtained with System.getProperty( ):

System.out.println(System.getProperty("java.specification.version"));

Running this on Java 2 prints “1.2”, as in JDK 1.2. Alas, not everyone is completely honest. Kaffe 1.5 certainly has some features of Java 2, but it is not yet a complete implementation of the Java 2 libraries. Yet it happily reports itself as “1.2” also. Caveat hactor!

Accordingly, you may want to test for the presence or absence of particular classes. One way to do this is with Class.forName("class") , which throws an exception if the class cannot be loaded -- a good indication that it’s not present in the runtime’s library. Here is code for this, from an application wanting to find out whether the JDK 1.1 or later components are available:

/** Test for JDK >= 1.1 */ public class TestJDK11 { public static void main(String[] a) { // Check for JDK >= 1.1 try { Class.forName("java.lang.reflect.Constructor"); } catch (ClassNotFoundException e) { String failure = "Sorry, but this version of MyApp needs \n" + ...

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.