Do resource bundles in Java support runtime string substitution?

前端 未结 8 752
夕颜
夕颜 2020-12-25 10:32

Can you do the following with a Java ResourceBundle?

In the properties file...

example.dynamicresource=You currently have {0} accounts.
8条回答
  •  独厮守ぢ
    2020-12-25 11:08

    MessageFormoat#format will work for the case like:

    greetingTo=Have Param, saying hello {0}
    

    You can declare two methods like this where RB is a instance of ResourceBundle:

    /**This is a method that takes the param to substitute the placeholder**/
    public String getString(String key, Object... params  ) {
        try {
            return MessageFormat.format(this.RB.getString(key), params);
        } catch (MissingResourceException e) {
            return "[" + key + "]";
        }
    }
    
    /**Without a param, this will derectly delegate to ResourceBundle#getString**/
    public String getString(String key) {
        try {
            return this.RB.getString(key);
        } catch (MissingResourceException e) {
            return "[" + key + "]";
        }
    } 
    

提交回复
热议问题