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 " + "a Java Runtime based on Java JDK 1.1 or later"; System.err.println(failure); throw new IllegalArgumentException(failure); } System.out.println("Happy to report that this is JDK1.1"); // rest of program would go here... return; } }
To check if the runtime includes the Swing components with their final names,[9] you could use:
Class.forName("javax.swing.JButton");
It’s important to distinguish between testing this at compile
time and at runtime. In both cases, this code must be compiled on a
system that includes the classes you are testing for -- JDK 1.1
and Swing, respectively. These tests are only attempts to help the
poor backwaters Java runtime user trying to run your up-to-date
application. The goal is to provide this user with a message more
meaningful than the simple “class not found” error that
the runtime will give. It’s also important to note that this
test becomes unreachable if you write it inside any code that depends
on the code you are testing for. The check for Swing won’t ever
see the light of day on a JDK 1.1 system if you write it in the
constructor of a JPanel
subclass (think about it).
Put the test early in the main flow of your application, before any
GUI objects are constructed. Otherwise the code will just sit there
wasting space on Java 2 systems and never getting run on Java 1.1
systems.
As for what the class Class
actually does,
we’ll defer that until Chapter 25.
[9] Old-timers will remember that on
the preliminary Swing releases, the name of this class was
com.sun.java.swing.JButton
.
3.22.41.235