0

Freemarker や Velocity (または JSP コンテナー) がこれらのツールをドラッグすることなくこれを達成する方法と同様に、プロパティ拡張を使用してインラインで文字列を置き換えることができる Apache Commons または同様の API を思い出すようです。この API が何であるか思い出せますか? 明らかに、名前は正しくありませんが、構造は次のようになります。

Person person = ...;
String expanded = SomeAPI.expand(
                  "Hi ${name}, you are ${age} years old today!", 
                  person);

これを達成する方法(たとえば、フォーマッターを使用)に関する他の提案は探していません。既存のAPIだけです。

4

2 に答える 2

3

MessageFormatあなたが探しているものかもしれません:

final MessageFormat format = new MessageFormat("Hi {0}, you are {1, number, #} years old today!");
final String expanded = format.format(new Object[]{person.getName(), person.getAge()});

CのようなものもありますString.format

final String expanded = String.format("Hi %1s, you are %2s years old today!", person.getName(), person.getAge());

テスト:

public static void main(String[] args) {
    final MessageFormat format = new MessageFormat("Hi {0}, you are {1,number,#} years old today!");
    System.out.println(format.format(new Object[]{"Name", 15}));
    System.out.println(String.format("Hi %1s, you are %2s years old today!", "Name", 15));
}

出力:

Hi Name, you are 15 years old today!
Hi Name, you are 15 years old today!
于 2013-03-07T17:31:48.233 に答える
1

これは、Apache Commons LangBeanUtilsを使用してトリックを実行する必要があります:

  StrSubstitutor sub = new StrSubstitutor(new BeanMap(person));

  String replaced = sub.replace("Hi ${name}, you are ${age} years old today!");
于 2013-03-07T19:04:08.293 に答える