String replacement in java, similar to a velocity template

前端 未结 8 1374
小鲜肉
小鲜肉 2020-11-28 04:59

Is there any String replacement mechanism in Java, where I can pass objects with a text, and it replaces the string as it occurs.
For example, the text is :

8条回答
  •  星月不相逢
    2020-11-28 05:34

    My preferred way is String.format() because its a oneliner and doesn't require third party libraries:

    String message = String.format("Hello! My name is %s, I'm %s.", name, age); 
    

    I use this regularly, e.g. in exception messages like:

    throw new Exception(String.format("Unable to login with email: %s", email));
    

    Hint: You can put in as many variables as you like because format() uses Varargs

提交回复
热议问题