一、场景
模版: 邀请了加入协作
参数:
operatorName="AAA"
affectedName="BBB"
渲染结果:AAA邀请了BBB加入协作
张口就来:
text = template.replaceAll("","AAA")
text = text.replaceAll("","BBB")
如果operatorName中包含也会被替换,这就尴尬了
二、实现
先正则匹配模版,替换模版匹配到的文本,开发了两个方法,一个是map参数,另一个反射更加灵活,可能性能不够优秀,可以做本地缓存class-fileds
import java.lang.reflect.Field;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @Author: BillYu
* @Description: 模版消息内容填充
* @Date: Created in 14:07 2020-12-01.
*/
public class StringTemplateUtil {
private static Pattern pattern = Pattern.compile("\\{\\w+\\}");
public static String processTemplate(String template, Map<String, Object> params){
Matcher m = pattern.matcher(template);
StringBuffer sb = new StringBuffer();
while (m.find()) {
String param = m.group();
Object value = params.get(param.substring(1, param.length() - 1));
m.appendReplacement(sb, value==null ? "null" : value.toString());
}
m.appendTail(sb);
return sb.toString();
}
/**
* 通用,反射速度稍慢,不用分装成map,直接用object
* @param template
* @param content
* @return
*/
public static String processTemplate(String template, Object content){
Matcher m = pattern.matcher(template);
StringBuffer sb = new StringBuffer();
while (m.find()) {
String param = m.group();
String fieldName = param.substring(1, param.length() - 1);
Object value = null;
try {
Field field = content.getClass().getDeclaredField(fieldName);
//设置对象的访问权限,保证对private的属性的访问
field.setAccessible(true);
value = field.get(content);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
m.appendReplacement(sb, value==null ? "null" : value.toString());
}
m.appendTail(sb);
return sb.toString();
}
}
更多方法参考 其他博客