Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

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" + ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata