I put together a small test implementation of this. The main idea is to call format and go to the format string and map objects, as well as the names that they have locally.
The conclusion is as follows:
My dog ββis called fido, and Jane Doe belongs to him.
public class StringFormatter { private static final String fieldStart = "\\$\\{"; private static final String fieldEnd = "\\}"; private static final String regex = fieldStart + "([^}]+)" + fieldEnd; private static final Pattern pattern = Pattern.compile(regex); public static String format(String format, Map<String, Object> objects) { Matcher m = pattern.matcher(format); String result = format; while (m.find()) { String[] found = m.group(1).split("\\."); Object o = objects.get(found[0]); Field f = o.getClass().getField(found[1]); String newVal = f.get(o).toString(); result = result.replaceFirst(regex, newVal); } return result; } static class Dog { public String name; public String owner; public String gender; } public static void main(String[] args) { Dog d = new Dog(); d.name = "fido"; d.owner = "Jane Doe"; d.gender = "him"; Map<String, Object> map = new HashMap<String, Object>(); map.put("d", d); System.out.println( StringFormatter.format( "My dog is named ${d.name}, and ${d.owner} owns ${d.gender}.", map)); } }
Note. This does not compile due to unhandled exceptions. But this makes the code much easier to read.
In addition, I do not like that you have to build the map in code yourself, but I do not know how to programmatically get the names of local variables. The best way to do this is to remember to place the object on the map immediately after creating it.
The following example shows the results you want in your example:
public static void main(String[] args) { Map<String, Object> map = new HashMap<String, Object>(); Site site = new Site(); map.put("site", site); site.name = "StackOverflow.com"; User user = new User(); map.put("user", user); user.name = "jjnguy"; System.out.println( format("Hello ${user.name},\n\tWelcome to ${site.name}. ", map)); }
I should also mention that I have no idea what Velocity is, so I hope this answer is appropriate.
jjnguy Sep 07 2018-10-10T00: 00Z
source share