これを達成する方法はありますか?
私はあなたが何を求めているのかを100%確信しているわけではありませんが、ここにいくつかの指針があります...
MessageFormat
APIのクラスを見てください。Formatter
クラスやString.format
メソッドにも興味があるかもしれません。
いくつかProperties
あり、形状のサブストリングを検索して置換したい場合は、次のよう#{ 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));
}
}
Propertiesオブジェクトではなく実際のPOJOがある場合は、次のようにリフレクションを実行できます。
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));
}
}
...しかし、それは醜くなってきています。これを解決するために、サードパーティのライブラリのいくつかをさらに深く掘り下げることを検討することをお勧めします。