String replacement in java, similar to a velocity template

前端 未结 8 1376
小鲜肉
小鲜肉 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:15

    Here's an outline of how you could go about doing this. It should be relatively straightforward to implement it as actual code.

    1. Create a map of all the objects that will be referenced in the template.
    2. Use a regular expression to find variable references in the template and replace them with their values (see step 3). The Matcher class will come in handy for find-and-replace.
    3. Split the variable name at the dot. user.name would become user and name. Look up user in your map to get the object and use reflection to obtain the value of name from the object. Assuming your objects have standard getters, you will look for a method getName and invoke it.

提交回复
热议问题