在Java中将i18n密钥字符串放在何处 [英] Where to place i18n key strings in Java

查看:60
本文介绍了在Java中将i18n密钥字符串放在何处的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中进行国际化时,可以为每条消息分配一个字符串键.在这些字符串键的放置位置上,最佳做法是什么.目标是允许轻松进行重构(例如,更改键名),干净且可读的代码,分离关注点,但即使从代码的不同部分进行调用,也仍然不能重复键/消息.

When doing internationalization in Java, you assign a string key to each message. What's the best practice, on where to place those string keys. Goal is to allow easy refactoring (eg. key name changes), clean and readable code, separation of concerns but still no duplication of keys/messages even if called from different parts of the code.

//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);
}

还有其他建议吗?哪个最好?我在Eclipse IDE上,如果这样可以使重构部分更加清晰.

Any other proposals? Which is best? I'm on Eclipse IDE, if that makes the refactoring part any clearer.

说明:在上述示例中,消息"的类型为ResourceBundle.

Clarification: in the above examples "messages" is of type ResourceBundle.

推荐答案

我总是将这样的界面用于列出我的键的接口. Interace的名称主要是DESC =问题/简短描述/主题和键值. 这样,您可以制作一些漂亮的界面和一些常规界面,例如确定或中止键.

i always using for such stuff an interface where my keys are listed. The name of the Interace is mostly DESC=Issue/short describtion/topic and the keys values. This way you can make some nice Interface and some general Interface e.g. for OK or Abort keys.

// 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);
}

这篇关于在Java中将i18n密钥字符串放在何处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆