Monday, December 26, 2005

Simplified resource bundle handling with osgi.util.NLS

In eclipse 3.1 there is a new package org.eclipse.osgi.util.NLS. This class allows you to have simple access to a resource bundle.
public class MyMessages extends NLS {
private static final String BUNDLE_NAME = "gr.scharf.MyMessages"; //$NON-NLS-1$

public static String HELLO_WORLD;
public static String HELLO_SOMETHING;

static {
// initialize resource bundles
NLS.initializeMessages(BUNDLE_NAME, MyMessages.class);
}
}

And in the file gr/scharf/MyMessages.properties I put:
  HELLO_WORLD=Hello world!
HELLO_SOMETHING=Hello {0}!


Then access to the properties is very simple:
    System.out.println(MyMessages.HELLO_WORLD);
System.out.println(MyMessages.bind(MyMessages.HELLO_SOMETHING,"world"));


Pretty cool, I think, because it loads the strings from the .properties file into the Messages class transparently. This also helps searching for strings in the code, because it is the same name as in the .properties file.

1 comment:

  1. Thanks!

    I found this post very useful.

    ReplyDelete