O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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" + ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required