首页  编辑  

用对象属性值替换模板中的对象属性名称占位符

Tags: /Java/   Date Created:
考虑如下情况:
有个字符串模板:
"Your name: ${name}, sex: ${sex}, email: ${info.email}, ..."
现在需要对其进行处理,用数据 user 对象 中对应的属性值替换相应的占位符,例如 ${name} 然后输出结果。其中 user 对象为:
{
  name: string,
  sex: string,
  info: {
      phone: string,
      email: string,
  }
}
如何实现类似效果?
用下面的方法即可:
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

  public static String replacePlaceHolders(String template, Object data) {
    BeanWrapper wrapper = new BeanWrapperImpl(data);
    Matcher matcher = Pattern.compile("\\$\\{([^}]+)}").matcher(template);
    StringBuffer result = new StringBuffer();
    while (matcher.find()) {
      String placeholder = matcher.group(1);
      Object value = wrapper.getPropertyValue(placeholder);
      String replace = value != null ? value.toString() : "";
      matcher.appendReplacement(result, replace);
    }
    matcher.appendTail(result);
    return result.toString();
  }
对于明确的属性值的替换,可以使用
PropertyPlaceholderHelper propertyPlaceholderHelper = new PropertyPlaceholderHelper("${", "}");
propertyPlaceholderHelper .replacePlaceholders(template, values);
例如:
public static void testProperties(){
        Properties properties = new Properties();
        properties.setProperty("name", "lisi");
        properties.setProperty("age", "29");
 
        PropertyPlaceholderHelper helper = new PropertyPlaceholderHelper("${","}");
        String value = "My name is ${name} and I am ${age} years old.";
        String result = helper.replacePlaceholders(value, properties);
 
        System.out.println(result);
}