You can use reflection to get the field values by name:
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String replaceTags(String rawText) {
Matcher m = Pattern.compile("%(.+?)%").matcher(rawText);
boolean result = m.find();
if (result) {
StringBuffer sb = new StringBuffer();
do {
m.appendReplacement(sb, Matcher.quoteReplacement(getField(m.group(1))));
result = m.find();
} while (result);
m.appendTail(sb);
return sb.toString();
}
return rawText.toString();
}
private String getField(String name) {
try {
return String.valueOf(this.getClass().getDeclaredField(name).get(this));
} catch (Exception e) {
throw new IllegalArgumentException("could not read value for field: " + name);
}
}
}
Ideone Demo
If you're on Java 9, you can simplify replaceTags() with a replacement function:
public String replaceTags(String rawText) {
return Pattern.compile("%(.+?)%").matcher(rawText)
.replaceAll(r -> Matcher.quoteReplacement(getField(r.group(1))));
}
If you have a JSON serialization library like Jackson, you can use it to handle the reflection automatically and build a map of values by field name:
Map<String, Object> fieldValues = new ObjectMapper()
.convertValue(this, new TypeReference<Map<String, Object>>() {});