Search code examples
javafreemarkerognl

java string subsitutions using object


Output of the below code is :

This is Raja from ${Address.Street} i did my ${Education.degree} from ${Education.university}

but what I need is

This is Raja from Namakkal i did my B.E from Anna University

is it possible to achieve by using Freemarker, OGNL or by using spring.

    public class Test 
    {   
     public static void main(String arg[]) throws TemplateModelException
      {

        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> address = new HashMap<String, Object>();             

        address.put("Street", "Namakkal");     

        Qualification qualification = new Test.Qualification();    

        map.put("Name", "Raja");
        map.put("Address", address);
        map.put("Education", qualification);


        StrSubstitutor strsub = new StrSubstitutor(map);

        String str = "This is ${Name} from ${Address.Street} i did my ${Education.degree} from ${Education.university}";

        System.out.println(strsub.replace(str));
    }

    public static class Qualification
    {
        public String getDegree()
        {
            return "B.E";
        }

        public String getUniversity()
        {
            return "Anna University";
        }
    }
}

please explain the simplest and effective way to achieve this.


Solution

  • You could do it with freemarker, using the StringTemplateLoader class. This class allows you to create templates from Strings, instead of reading them from files.