How do I avoid repetition in Java ResourceBundle strings?

后端 未结 2 942
名媛妹妹
名媛妹妹 2021-02-05 15:09

We had a lot of strings which contained the same sub-string, from sentences about checking the log or how to contact support, to branding-like strings containing the company or

2条回答
  •  孤城傲影
    2021-02-05 15:21

    If the string repetitions are localized in the sense that you know a certain string will be repeated but only within the same project such that sharing resource bundles is not a design nightmare, then you might consider breaking the strings down into multiple key-value parts. Separate the parts that repeat from those that do not and reuse the repeated parts. For example, lets say you have the following two strings you need to display:

    1. "The Red-capped Robin is a small passerine bird native to Australia. "
    2. "The Red-capped Robin is found in dryer regions across much of the continent."

    The resource bundle could be as follows:

    robin.name=The Red-capped Robin
    robin.native=is a small passerine bird native to Australia.
    robin.region=is found in dryer regions across much of the continent.
    

    and then combine the required parts where needed bundle.getString("robin.name")+bundle.getString(robin.native).

    One thing you need to be careful about though is that the grammar rules like subject predicate order etc. might not be the same in all languages. So you would need to be a little careful when splitting sentences.

提交回复
热议问题