Where to place I18N key strings in Java
•
Java
When Internationalizing in Java, you can assign a string key to each message What are best practices and where to place these string keys The goal is to allow easy refactoring (e.g. key name change), clean and readable code, and separate problems, but even if called from different parts of the code, the key / message will not be repeated
//bad way,strings directly in code messages.getString("hello_key");
–
// better way,use String constants public static final String HELLO_KEY = "hello_key"; ... messages.getString(HELLO_KEY);
–
// other (better?) way,put all keys in one huge central class public class AllMessageKeys { public static final String HELLO_KEY = "hello_key"; ... } public class Foo { ... messages.getString(AllMessageKeys.HELLO_KEY); }
–
// other (better?) way,put all keys in neighbor class public class FooMessageKeys { public static final String HELLO_KEY = "hello_key"; } public class Foo { ... messages.getString(FooMessageKeys.HELLO_KEY); }
Any other suggestions? Which is the best? I'm on the eclipse ide if this makes the refactoring part clearer
Note: in the above example, the type of "message" is resourcebundle
Solution
I always use something like this, an interface listed by my keys The name of interace is mainly desc = problem / short description / topic and key value
// other (better?) way,put all keys in neighbor class public interface DESCMessage { public static final String HELLO_KEY = "hello_key"; } public class Foo { ... messages.getString(DESCMessage.HELLO_KEY); }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码