Is there any way to achieve this?
I'm not 100% sure I understand what you're after, but here are some pointers...
Have a look at the MessageFormat
class in the API. You may also be interested in the Formatter
class and/or the String.format
method.
If you have some Properties
and you want to search and replace substrings of the shape #{ property.key }
you could also just do like this:
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));
}
}
If you have actual POJOs and not a Properties object, you could go through reflection, like this:
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));
}
}
... but it's getting ugly, and I suggest you consider digging deeper into some of the 3rd party libraries for solving this.