使用object的java字符串替换

时间:2014-05-29 08:33:54

标签: java freemarker ognl

以下代码的输出是:

这是Raja来自 $ {Address.Street} 我从 $ {Education.university} 做了 $ {Education.degree}

但我需要的是

来自 Namakkal的 Raja 我从安娜大学

做了 B.E

是否可以使用FreemarkerOGNL或使用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";
        }
    }
}

请解释实现这一目标的最简单有效的方法。

4 个答案:

答案 0 :(得分:2)

如果您想使用StrSubstitutor本身,可以通过扩展StrLookUp类来尝试使用自定义变量解析器。

示例:

StrSubstitutor strsub = new StrSubstitutor(new CustomLookUp(map));

...
...

private static class CustomLookUp extends StrLookup<Object> {

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

    public CustomLookUp(Map<String, Object> map) {
        this.map = map;
    }

    @Override
    public String lookup(String key) {
       // ...
       // Logic for resolving your variables.
       // ...
    }
}

答案 1 :(得分:0)

你可以使用StringTemplateLoader类通过freemarker完成。此类允许您从字符串创建模板,而不是从文件中读取它们。

答案 2 :(得分:0)

如果没有freemarker,您可以使用以下内容:

String str="This is "+(String)map.get("Name")+" from "+((Map)map.get("Address")).get("Street")+". I did my "+((Qualification)map.get("Education")).getDegree()+" from "+((Qualification)map.get("Education")).getUniversity()+".";

答案 3 :(得分:0)

带有弹簧反射的@Anoop示例实现

    @Override
    public String lookup(String key) {
        String[] keys = key.split("\\.");
        Object obj = map.get(keys[0]);
        for (int i = 1; i < keys.length; i++) {
            Class<?> clazz = obj.getClass();
            Field field = null;
            try {
                field = org.springframework.util.ReflectionUtils.findField(clazz, (keys[i]));
                org.springframework.util.ReflectionUtils.makeAccessible(field);
                obj = field.get(obj);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return (String) obj;
    }