Where to place i18n key strings in Java

前端 未结 8 2776
不思量自难忘°
不思量自难忘° 2021-02-20 04:10

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 refactori

8条回答
  •  走了就别回头了
    2021-02-20 04:33

    I also think the first is the worst choice. In most cases (the key is only used by one class) I would prefer the second solution with String constants.

    If the key is referenced from more than one class, the neighbor class is a better way (using an interface like @moohkooh mentioned).

    The solution with one central class creates a dependency magnet which is a bad design in my opinion. Neighbor interfaces with constants per package would be a better one.

    If you do not want a interface to hold the constants, you can use an enriched enum:

    public enum DESCMessage {
    
      HELLO("hello_key"),
      OTHER("other_key");
    
      private final String key;
    
      private DESCMessage(String key) {
        this.key = key;
      }
    
      public String key() {
        return key;
      }
    }
    

    This can be used as:

    messages.getString(DESCMessage.HELLO.key());
    

提交回复
热议问题