问题
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:

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"
becomesMessages.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:
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:

Then the proposed changes:

Related links
- eclipse.org/Getting and using Equinox OSGi
来源:https://stackoverflow.com/questions/3886978/configuring-string-externalization-in-eclipse-to-use-key-as-field-name