今天看到占位符,心血来潮,想自己实现一个简单的试试:
package com.ccm.templateproject.entity;
import lombok.Data;
import java.lang.reflect.Field;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Data
public class Action {
private String name;
private String address;
private String doSomething;
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
String s = "${name}去了${address}${doSomething}";
Action action = new Action();
action.setName("张梦婷");
action.setAddress("医院");
action.setDoSomething("看了妈妈");
System.out.println(parse(s,action));;
}
public static <T> String parse(String content,T t) throws NoSuchFieldException, IllegalAccessException {
Pattern pattern = Pattern.compile("\\$\\{(\\w+)\\}");
Matcher matcher = pattern.matcher(content);
while (matcher.find()){
//获取匹配到的字段名
String fieldName = matcher.group(1);
Field field = t.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
//要替换的子串
String replace = matcher.group(0);
content = content.replace(replace, (String)field.get(t));
}
return content;
}
}
看到输出,小小满足,收工!!!