Configuring string externalization in Eclipse to use ${key} as field name

11k Views Asked by At

Suppose I have a simple code like this:

public class ExternalizeStringDemo {
    public static void main(String[] args) {
        System.out.println("Hello world");
    }
}

Now, I want to externalize the greeting, perhaps to facilitate internationalization/localization/etc. Using Eclipse, I can use the String Externalization wizard (Source/Externalize Strings), and configure it like this:

alt text

I can proceed with the wizard and it will propose these changes:

  • Create file Personal Toys/src/Messages.java
  • Create file Personal Toys/src/messages.properties
  • Edit ExternalizeStringDemo.java
    • "Hello World" becomes Messages.getString("DEMO_GREETING")

My question is simple: can I ask Eclipse to externalize the access to use the key as field names instead? That is, I want the access to be e.g. Messages.DEMO_GREETING.

Note: if the [Substitution pattern] is simple ${key}, then the generated code is Messages."DEMO_GREETING", which is not a valid Java code.


If this is not possible, then what's the next best thing? (I'm thinking Eclipse regex find/replace?).

1

There are 1 best solutions below

1
On

Eclipse has a new string externalization mechanism that does exactly this; it uses its own new message bundle instead of Java's. You need to include the org.eclipse.osgi….jar in your project's build path to use it.

help.eclipse.org - Java development user guide > Reference > Wizards and Dialogs > Externalize Strings Wizard

  • Use Eclipse's string externalization mechanism
    • If unchecked the standard externalization mechanism is used, otherwise the new Eclipse string externalization mechanism is used.
    • Note: Only present if the project build path contains org.eclipse.osgi.util.NLS

The before-and-after is shown in the feature documentation:

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$
      ...
   }
}

Screenshots

The setup:

alt text

Then the proposed changes:

alt text

Related links