Is there any way to achieve this?
我不是100%肯定我了解您的要求,但是这里有一些提示…
如果您有一些属性,并且想要搜索和替换形状为#{property.key}的子字符串,您也可以这样做:
import java.util.Properties;
import java.util.regex.*;
class Test {
public static String process(String template, Properties props) {
Matcher m = Pattern.compile("#\{(.*?)\}").matcher(template);
StringBuffer sb = new StringBuffer();
while (m.find())
m.appendReplacement(sb, props.getProperty(m.group(1).trim()));
m.appendTail(sb);
return sb.toString();
}
public static void main(String[] args) {
Properties props = new Properties();
props.put("user.name", "Jon");
props.put("user.email", "jon.doe@example.com");
String template = "Name: #{ user.name }, email: #{ user.email }";
// Prints "Name: Jon, email: jon.doe@example.com"
System.out.println(process(template, props));
}
}
如果您有实际的POJO而不是Properties对象,则可以进行反射,如下所示:
import java.util.regex.*;
class User {
String name;
String email;
}
class Test {
public static String process(String template, User user) throws Exception {
Matcher m = Pattern.compile("#\{(.*?)\}").matcher(template);
StringBuffer sb = new StringBuffer();
while (m.find()) {
String fieldId = m.group(1).trim();
Object val = User.class.getDeclaredField(fieldId).get(user);
m.appendReplacement(sb, String.valueOf(val));
}
m.appendTail(sb);
return sb.toString();
}
public static void main(String[] args) throws Exception {
User user = new User();
user.name = "Jon";
user.email = "jon.doe@example.com";
String template = "Name: #{ name }, email: #{ email }";
System.out.println(process(template, user));
}
}
…但是它变得越来越丑陋,我建议您考虑更深入地研究一些第三方库来解决此问题.