# Message Bundles

## Description

Standard Java ResourceBundles have quite inefficient space characteristics. Since a running Eclipse tends to have many externalized messages, we have implemented a new message bundle system to be used in Eclipse. The mechanism is quite simple and completely generic - it can be used anywhere.

### Summary of the new approach:

- `messages.properties` - this file is same as before except all keys need to be valid Java identifiers.
- Each message file has a corresponding Java class.
- Each key/value pair in the file has a `public static String` field whose name is the same as the message key.
- When message bundles are loaded, the values of the fields are set to be the values from the `messages.properties` files.
- The message properties files are purged from memory.

### When creating a new message:

- Create a field in your `Messages.java` file.
- Create a key/value pair in your `messages.properties` file where the key name matches the field name,
- To reference the message, simply reference the field (e.g. `Messages.my_key`) rather than the standard lookup.

## Example Files:

### Client Code

#### Old Code:

    public class MyClass {
      public void myMethod() {
        String message;
        ...
        // no args
        message = Messages.getString("key.one"); //$NON-NLS-1$
        ...
        // bind one arg
        message = MessageFormat.format(Messages.getString("key.two"), new Object[] {"example usage"}); //$NON-NLS-1$ //$NON-NLS-2$
        ...
      }
    }

#### New Code:

    public class MyClass {
      public void myMethod() {
        String message;
        ...
        // no args
        message = Messages.key_one;
        ...
        // bind one arg
        message = NLS.bind(Messages.key_two, "example usage"); //$NON-NLS-1$
        ...
      }
    }

### Messages.java

#### Old Code:

    public class Messages {
      private static final String BUNDLE_NAME = "org.eclipse.core.utils.messages"; //$NON-NLS-1$
      private static final ResourceBundle bundle = ResourceBundle.getBundle(BUNDLE_NAME);

      public static String getString(String key) {
        try {
          return bundle.getString(key);
        } catch (MissingResourceException e) {
          return key;
        }
      }
    }

#### New Code:

    import org.eclipse.osgi.util.NLS;

    public class Messages extends NLS {
      private static final String BUNDLE_NAME = "org.eclipse.core.utils.messages"; //$NON-NLS-1$

      public static String key_one;
      public static String key_two;
      ...
      static {
        NLS.initializeMessages(BUNDLE_NAME, Messages.class);
      }
    }

### messages.properties

#### Old Code:

    key.one = Hello world.
    key.two = This is an {0} of binding with one argument.

#### New Code:

    key_one = Hello world.
    key_two = This is an {0} of binding with one argument.