Java Reference
In-Depth Information
Discussion
Although Java is meant to be portable, Java runtimes have some significant variations. So-
metimes you need to work around a feature that may be missing in older runtimes, but you
want to use it if it's 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 Sys-
tem.getProperty() :
System.out.println(System.getProperty("java.specification.version"));
Alternatively, and with greater generality, you may want to test for the presence or absence
of particular classes. One way to do this is with Class.forName("class") (see Chapter 23 ),
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 common Swing UI components are available (they normally would be in any
modern standard Java SE implementation, but not, for example, in the pre-museum-piece
JDK 1.1, nor in the Java-based Android runtime). The javadoc for the standard classes re-
ports the version of the JDK in which this class first appeared, under the heading “Since.” If
there is no such heading, it normally means that the class has been present since the begin-
nings of Java:
starting/CheckForSwing.java
public
public class
class CheckForSwing
CheckForSwing {
public
public static
static void
void main ( String [] args ) {
try
try {
Class . forName ( "javax.swing.JButton" );
} catch
catch ( ClassNotFoundException e ) {
String failure =
"Sorry, but this version of MyApp needs \n" +
"a Java Runtime with JFC/Swing components\n" +
"having the final names (javax.swing.*)" ;
// Better to make something appear in the GUI. Either a
// JOptionPane, or: myPanel.add(new Label(failure));
System . err . println ( failure );
}
// No need to print anything here - the GUI should work...
}
}
Search WWH ::




Custom Search