Return-Path: Received: from po10.mit.edu (po10.mit.edu [18.7.21.66]) by po10.mit.edu (Cyrus v2.1.5) with LMTP; Thu, 21 Aug 2003 03:06:58 -0400 X-Sieve: CMU Sieve 2.2 Received: from fort-point-station.mit.edu by po10.mit.edu (8.12.4/4.7) id h7L76ubU008665; Thu, 21 Aug 2003 03:06:56 -0400 (EDT) Received: from hermes.sun.com (hermes.sun.com [64.124.140.169]) by fort-point-station.mit.edu (8.12.4/8.9.2) with SMTP id h7L76tmM003943 for ; Thu, 21 Aug 2003 03:06:55 -0400 (EDT) Date: 21 Aug 2003 00:00:35 -0800 From: "SDN - Core Java Technologies Tech Tips" To: alexp@mit.edu Message-Id: <40341097-60885932@hermes.sun.com> Subject: Core Java Technologies Tech Tips, August, 19, 2003 (Formatting Messages, Unloading/Reloading Classes) Mime-Version: 1.0 Content-Type: text/html; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit X-Mailer: SunMail 1.0 X-Spam-Score: 2.2 X-Spam-Level: ** (2.2) X-Spam-Flag: NO X-Scanned-By: MIMEDefang 2.28 (www . roaringpenguin . com / mimedefang) Core Java Technologies Technical Tips
.
.
Core Java Technologies Technical Tips
.
   View this issue as simple text August 19, 2003    

In this Issue

Welcome to the Core Java Technologies Tech Tips, August 19, 2003. Here you'll get tips on using core Java technologies and APIs, such as those in Java 2 Platform, Standard Edition (J2SE).

This issue covers:

-Formatting Messages With Variable Content
-Unloading and Reloading Classes

These tips were developed using Java 2 SDK, Standard Edition, v 1.4.

This issue of the Core Java Technologies Tech Tips is written by John Zukowski, president of JZ Ventures, Inc.

See the Subscribe/Unsubscribe note at the end of this newsletter to subscribe to Tech Tips that focus on technologies and products in other Java platforms.

.
.

FORMATTING MESSAGES WITH VARIABLE CONTENT

Internationalization is the process of designing an application to work with multiple languages and in regions around the world. This not only involves translating text labels to other languages. It also also means displaying information such as dates and times in a format appropriate for that particular region of the globe.

The first step involved in internationalizing text labels and messages is to move everything into resource bundles. For each quoted string you want the user to see, you create an entry in a resource bundle. Then, you change the code to dynamically look up the text label or message based on the locale of the user. When you do this correctly, a user in the United States might see Help as the label for a help menu, while a Spanish user would see Ayuda.

This technique works perfectly well for straight text-to-text translations, where you are always displaying a "whole" message. However this technique doesn't work for compound messages, where you need to combine several pieces of a message into one longer message. For instance, consider the following message:

   Hello, John. Good luck.

You might think that you could simply use string concatenation, and build the compound message by appending multiple strings together:

   System.out.println(
     "Hello, " +
     name +
     ". Good luck.")

You might also assume that you could localize the compound message by moving the Hello and Good luck strings into resource bundles. This might work, but what happens when you get to a language where the form of the greeting becomes something like:

   Hello and good luck, John.

You could break up the resource bundle strings into a prefix part before the name, and a suffix part after the name. But this complicates things for translators because they must know what pieces go together. A better approach is to have one text string, with a variable holder in the middle for the name.

For English, that string might be:

   Hello, {0}. Good luck.

Seeing that whole string, a translator for Spanish might realize it is better to put hello and good luck together, as follows:

   Hola y buena suerte, {0}.

When it's time to actually display the message, the MessageFormat class of the java.text package can be used to replace the variables. MessageFormat takes a set of objects, formats them, and inserts the formatted strings into a pattern. The pattern could be something like "Hello, {0}. Good luck."

To use MessageFormat, you start by creating a formatter:

   String pattern = ...; // from bundle
   Locale aLocale = ...; // the Locale

   MessageFormat formatter = new MessageFormat(pattern);
   formatter.setLocale(aLocale);

For each pattern, you could create different MessageFormat objects. However you can also reuse the MessageFormat object with another pattern by calling the applyPattern method with the new pattern template. Remember to do this after changing locales:

   formatter.setLocale(aNewLocale);
   formatter.applyPattern(aPatternForNewLocale);

After you have the formatter, you need to generate the output message. To do this, you pass in an array of arguments, where each {#} in the pattern is replaced, based on its index in the array. For instance, a one element array is needed for the pattern "Hello, {0}. Good luck." The one element in the array contains the text that will be inserted at position 0 in the string. Here's an example -- it's a one element array that contains the string "John" for insertion into the previous pattern:

  Object messageArgs[] = {"John"};

To generate the output, you call the format method of MessageFormat, specifying the message arguments:

   System.out.println(formatter.format(messageArgs));

The following program, HelloGoodLuck, demonstrates the use of MessageFormat. To keep things simple, the program doesn't use resource bundles:

   import java.text.*;
   import java.util.*;

   public class HelloGoodLuck {
     public static void main(String args[]) {
       String pattern = "Hello, {0}. Good luck.";
       Locale aLocale = Locale.US;
       MessageFormat formatter = new MessageFormat(
                                   pattern, aLocale);
       Object messageArgs[] = {"John"};
       System.out.println(
                        formatter.format(messageArgs));
       // Pass in command line args
       if (args.length != 0) {
         System.out.println(formatter.format(args));
       }
     }
   }

The HelloGoodLuck program produces a second message if you pass in a name on the command line. If you run the program with the following command:

   java HelloGoodLuck Spot

You should see the output:

   Hello, John. Good luck.
   Hello, Spot. Good luck.

Using MessageFormat is not limited to text substitution. You can also use it to format numbers and dates, that is, without having to use the NumberFormat and DateFormat classes. The javadoc for the MessageFormat class describes all the support available.

After the argument index part of {#}, you can specify a format type and a style (separated by commas). For instance, in the case of a date, you can specify a short, medium, long, or full to map to the DateFormat constants. If the argument type is a Date, and the MessageFormat maps that argument to "{1,date,long}", you would see the long format for a date displayed (in a format appropriate for the locale). You can also display dates with a "time" type, using the same short, medium, long, full options. For a number, the available styles include integer, currency, and percent. If you don't like the built-in styles, and know the pattern strings of SimpleDateFormat and DecimalFormat, you can also specify those directly.

To demonstrate, the following MessageFormat pattern uses time, date, and number:

   At the tone, the time is now {0, time, short} 
   on {0, date, long}. 
   You now owe us {1, number, currency}.

If you then provided a Date and Number as the input argument, it would generate output for US-English and German locales.

ExtendedFormat

And here is the program that produces that output. To keep the demonstration simple, resource bundles were not used. However, the strings in the pattern and germanPattern variables in the program should be located in resource bundles.

   import java.text.*;
   import java.util.*;
   import java.io.*;
   import java.awt.*;
   import javax.swing.*;

   public class ExtendedFormat {
     public static void main(String args[]) {
       String pattern = 
         "At the tone, the time is now {0, time, short}" + 
         " on {0, date, long}." +
         " You now owe us {1, number, currency}.";
       String germanPattern =
         "Beim Zeitton ist es {0, time, short} Uhr" +
         " am {0, date, long}." +
         " Sie schulden uns jetzt {1, number, currency}.";
       
       StringWriter sw = new StringWriter(100);
       PrintWriter out = new PrintWriter(sw, true);
       MessageFormat formatter = 
                 new MessageFormat(pattern, Locale.US);
       Object messageArgs[] = 
                     {new Date(), new Double(9000.12)};
       out.println(formatter.format(messageArgs));
       formatter.setLocale(Locale.GERMAN);
       // Need to reset pattern after changing locales
       formatter.applyPattern(germanPattern);
       out.println(formatter.format(messageArgs));
       out.close();
       // Put output in window
       JFrame frame = new JFrame("Extended Format");
       frame.setDefaultCloseOperation(
                                 JFrame.EXIT_ON_CLOSE);
       JTextArea ta = new JTextArea(sw.toString());
       JScrollPane pane = new JScrollPane(ta);
       frame.getContentPane().add(
                            pane, BorderLayout.CENTER);
       frame.setSize(500, 100);
       frame.show();
     }
   }

There is much more to properly internationalizing your applications than using MessageFormat. For more information on the use of resource bundles (where all these string patterns should come from), see the May 21, 1998 Tech Tip, "Resource Bundles". Also, for more information on formatting date and time strings, see the June 24, 2003 Tech Tip, "Internationalizing Dates, Times, Months, and Days of the Week".

.
.

UNLOADING AND RELOADING CLASSES

The July 22, 2003 Tech Tip titled "Compiling Source Directly From a Program" offered a way to compile source files directly from your Java program. It presented a simple editor in which you can name a class and provide the source. That approach works fine, provided the class is not one that you already compiled and loaded during the current execution run. If indeed you previously compiled and loaded the class, you can't then edit it and recompile it using the approach covered in the previous Tech Tip. The issue here is the underlying class loader. All classes loaded through the system class loader will never be unloaded. To allow the program to let you reedit the source for a class, and then recompile and reload it, you need to work with a different class loader. In this tip, you'll learn how to create a custom class loader, one that lets you load your newly compiled class (or any c! lass). You'll also learn how to discard the class such that the next time you compile the class, the newly compiled class is loaded.

An instance of the ClassLoader class of the java.lang package is responsible for loading all classes. For system classes, that class loader is available through the getSystemClassLoader method of ClassLoader. For user classes, if that class is already loaded, you can ask for the ClassLoader with the getClassLoader method of Class.

In the RunIt program from the earlier Tech Tip, the forName method of Class was used to load the class data (that is, to get an instance of Class). If you want to use a different class loader, you have to use the loadClass method of ClassLoader to load the class data. In other words, you need to code this:

   String className = ...;
   Class aClass = loader.loadClass(className);   

instead of this:

   String className = ...;
   Class aClass = Class.forName(className);   

Functionally, the two code blocks above are identical when loading through the same class loader. The first block loads the class through the same loader as where the code is found. The second loads the class through the class loader specified by the loader variable. In both cases, you would then call something like newInstance to create an instance of the class.

Repeated calls to Class.forName load the same class (assuming the class loader of the calling class doesn't change). Repeated calls to loader.loadClass load the same class. However, the second block allows you to reload a class. To do that, you create a new ClassLoader:

   String className = ...;
   // create new loader instance
   ClassLoader loader = ...; 
   Class aClass = loader.loadClass(className);

In this particular code block, a new loader is created between calls to loadClass. If the class definition for className changes between calls, the new version of the class is loaded the second time through.

If you change the RunIt program to use this mechanism, you can edit the source after compiling and running the program. The program should generate output appropriate to the new source, not the old.

The only thing left is where to get the ClassLoader. The ClassLoader class is itself an abstract class. Predefined loaders include the SecureClassLoader of java.security, which adds permission support, and the URLClassLoader of java.net. Of the two predefined loaders, only URLClassLoader offers support for public construction through either its constructors or static newInstance methods. See the documentation for URLClassLoader for further details.

Creating a URLClassLoader involves creating an array of URL objects. These URL objects serve as the locations that the custom class loader uses to find classes. You specify the elements of the array similarly to the way you specify path elements for the CLASSPATH environment variable, where the path elements are separated by a ; on Windows and a : on Unix machines. Each element in the URL array can be a located locally or on a remote host. Anything ending in a "/" is presumed to be a directory. Anything else is presumed to be a JAR file.

For instance, if you want to create a ClassLoader that works like the default classpath, that is, only searching in the current directory, you can code the following:

   File file = new File(".");
   ClassLoader loader = new URLClassLoader(
     new URL[] {file.toURL()}
   );

The first line creates a File object, referencing the current directory. The second line calls the URLClassLoader constructor. Passed into the constructor is an array of one URL object: the URL to the File.

If you change the RunIt program to include the following code, recompile it, and run it, the program will discard the loaded classes between runs and reload them. Notice that unlike the RunIt program in the earlier Tech Tip, the following code does not create an instance of the class to invoke the main method. There is no need to create an instance of the class because the main method is static,

   // Create new class loader 
   // with current dir as CLASSPATH
   File file = new File(".");
   ClassLoader loader = new URLClassLoader(
     new URL[] {file.toURL()}
   );
   // load class through new loader
   Class aClass = loader.loadClass(className.getText());
   // run it
   Object objectParameters[] = {new String[]{}};
   Class classParameters[] =
     {objectParameters[0].getClass()};
   Method theMethod = aClass.getDeclaredMethod(
     "main", classParameters);
   // Static method, no instance needed
   theMethod.invoke(null, objectParameters);

Here's the complete code example, with the RunIt program renamed to RunItReload.

   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
   import java.io.*;
   import java.net.*;
   import java.lang.reflect.*;

   public class RunItReload extends JFrame {
     JPanel contentPane;
     JScrollPane jScrollPane1 = new JScrollPane();
     JTextArea source = new JTextArea();
     JPanel jPanel1 = new JPanel();
     JLabel classNameLabel = new JLabel("Class Name");
     GridLayout gridLayout1 = new GridLayout(2,1);
     JTextField className = new JTextField();
     JButton compile = new JButton("Go");
     Font boldFont = new java.awt.Font(
                                  "SansSerif", 1, 11);

     public RunItReload() {
       super("Editor");
       setDefaultCloseOperation(EXIT_ON_CLOSE);
       contentPane = (JPanel) this.getContentPane();
       this.setSize(400, 300);
       classNameLabel.setFont(boldFont);
       jPanel1.setLayout(gridLayout1);
       compile.setFont(boldFont);
       compile.setForeground(Color.black);
       compile.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
           try {
             doCompile();
           } catch (Exception ex) {
             System.err.println(
                   "Error during save/compile: " + ex);
             ex.printStackTrace();
           }
         }
       });
       contentPane.add(
                    jScrollPane1, BorderLayout.CENTER);
       contentPane.add(jPanel1, BorderLayout.NORTH);
       jPanel1.add(classNameLabel);
       jPanel1.add(className);
       jScrollPane1.getViewport().add(source);
       contentPane.add(compile, BorderLayout.SOUTH);
     }
     public static void main(String[] args) {
       Frame frame = new RunItReload();
       // Center screen
       Dimension screenSize =
         Toolkit.getDefaultToolkit().getScreenSize();
       Dimension frameSize = frame.getSize();
       if (frameSize.height > screenSize.height) {
         frameSize.height = screenSize.height;
       }
       if (frameSize.width > screenSize.width) {
         frameSize.width = screenSize.width;
       }
       frame.setLocation(
         (screenSize.width - frameSize.width) / 2,
         (screenSize.height - frameSize.height) / 2);
       frame.show();
     }
     private void doCompile() throws Exception {
       // write source to file
       String sourceFile = className.getText() + ".java";
       FileWriter fw = new FileWriter(sourceFile);
       fw.write(source.getText());
       fw.close();
       // compile it
       int compileReturnCode =
         com.sun.tools.javac.Main.compile(
             new String[] {sourceFile});
       if (compileReturnCode == 0) {
         // Create new class loader 
         // with current dir as CLASSPATH
         File file = new File(".");
         ClassLoader loader = 
         new URLClassLoader(new URL[] {file.toURL()});
         // load class through new loader
         Class aClass = loader.loadClass(
                                  className.getText());
         // run it
         Object objectParameters[] = {new String[]{}};
         Class classParameters[] =
                     {objectParameters[0].getClass()};
         Method theMethod = aClass.getDeclaredMethod(
                              "main", classParameters);
         // Static method, no instance needed
         theMethod.invoke(null, objectParameters);
       }
     }
   }

You need to compile and execute this program in a slightly different way than you did for the RunIt program in the earlier Tech Tip. Because the custom class loader is using the current directory as the place where reloadable classes need to come from, you can't load the actual RunItReload class from the same classpath. Otherwise, the system class loader will load the compiled class from the same location (and class loader). You need to tell the compiler to send the compiled classed for RunItReload to a different location. You run the program with that other location in the classpath, not with "." in it. Remember that you need to include tools.jar in the classpath to compile. The following command sends the newly compiled .class files for RunItReload to the XYZ subdirectory. Feel free to pick a different subdirectory name. (Although the command is shown on multip! le lines it needs to go on one line):

In Windows:

    mkdir XYZ
    javac -d XYZ -classpath 
     c:\j2sdk1.4.2\lib\tools.jar RunItReload.java

In Unix:

    mkdir XYZ
    javac -d XYZ -classpath 
     /homedir/jdk14/j2sdk1.4.2/lib/tools.jar 
     RunItReload.java

Replace homedir with your actual home directory.

If you get an error that the system cannot find the path specified, be sure to create the XYZ directory before compilation.

As before, you need to include the tools.jar file in your runtime classpath, and you need to include the XYZ directory for the actual RunItReload program. To run the program, issue the following command. (Again, although the command is shown on multiple lines, it needs to go on one line).

In Windows:

    java -classpath 
     c:\j2sdk1.4.2\lib\tools.jar;XYZ RunItReload

In Unix:

   java -classpath 
      /homedir/jdk14/j2sdk1.4.2/lib/tools.jar:
      XYZ RunItReload

The XYZ here is carried over from the prior javac step. The target directory for compilation (specified after -d) must match the runtime classpath.

Running the program displays the GUI. Then you can:

  1. Enter the name of the class, such as Sample2, to be compiled in the JTextField.
  2. Enter the source code in the JTextArea. Here's the source code for Sample2:
        public class Sample2 {
          public static void main(String args[]) {
            System.out.println(new java.util.Date());
            // System.out.println("Hello, World!");
          }
        }
    
  3. Click the Go button.

Sample2

Output is sent to the console. For example, Sample2 should produce output that looks something like this:

  Tue Aug 19 11:25:16 PDT 2003

Comment out the line that prints the date, and uncomment the line that prints "Hello World". Click the Go button. You should now see the following in your console:

  Hello, World!

You see a different line displayed because a new class loader was created, one that unloaded previously loaded classes.

.
.
.

Reader Feedback

  Very worth reading    Worth reading    Not worth reading 

If you have other comments or ideas for future technical tips, please type them here:

 

Have a question about Java programming? Use Java Online Support.

.
.

IMPORTANT: Please read our Terms of Use, Privacy, and Licensing policies:
http://www.sun.com/share/text/termsofuse.html
http://www.sun.com/privacy/
http://developer.java.sun.com/berkeley_license.html


Comments? Send your feedback on the Core Java Technologies Tech Tips to: http://developers.sun.com/contact/feedback.jsp?category=sdn

Subscribe to other Java developer Tech Tips:

- Enterprise Java Technologies Tech Tips. Get tips on using enterprise Java technologies and APIs, such as those in the Java 2 Platform, Enterprise Edition (J2EE).
- Wireless Developer Tech Tips. Get tips on using wireless Java technologies and APIs, such as those in the Java 2 Platform, Micro Edition (J2ME).

To subscribe to these and other JDC publications:
- Go to the JDC Newsletters and Publications page, choose the newsletters you want to subscribe to and click "Update".
- To unsubscribe, go to the subscriptions page, uncheck the appropriate checkbox, and click "Update".


ARCHIVES: You'll find the Core Java Technologies Tech Tips archives at:
http://java.sun.com/jdc/TechTips/index.html


Copyright 2003 Sun Microsystems, Inc. All rights reserved.
4150 Network Circle, Santa Clara, CA 95054 USA.


This document is protected by copyright. For more information, see:
http://java.sun.com/jdc/copyright.html


Java, J2SE, J2EE, J2ME, and all Java-based marks are trademarks or registered trademarks (http://www.sun.com/suntrademarks/) of Sun Microsystems, Inc. in the United States and other countries.

Sun Microsystems, Inc.
.
.


Please unsubscribe me from this newsletter.