javastringreflectionvelocitystring-interpolation

String replacement in java, similar to a velocity template


Is there any String replacement mechanism in Java, where I can pass objects with a text, and it replaces the string as it occurs? For example, the text is:

Hello ${user.name},
Welcome to ${site.name}. 

The objects I have are user and site. I want to replace the strings given inside ${} with its equivalent values from the objects. This is same as we replace objects in a velocity template.


Solution

  • Use StringSubstitutor from Apache Commons Text.

    Dependency import

    Import the Apache commons text dependency using maven as bellow:

    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-text</artifactId>
        <version>1.10.0</version>
    </dependency>
    

    Example

    Map<String, String> valuesMap = new HashMap<String, String>();
    valuesMap.put("animal", "quick brown fox");
    valuesMap.put("target", "lazy dog");
    String templateString = "The ${animal} jumped over the ${target}.";
    StringSubstitutor sub = new StringSubstitutor(valuesMap);
    String resolvedString = sub.replace(templateString);