开发者

Advance MessageFormat with introspection

I'm looking for the following feature describe below. The MessageFormat of the sun api doesn't fit my need & the Spring El expression too maybe.

Assuming that we have a person Object with a name:

Person person = new Person();
person.setName("fredop");
person.setAge("25");

String messageFormat="My name is {Person.name}, i'm {Person.age} years old""

System.out.p开发者_开发百科rintln(Translate(person,messageFormat);

In the translate method, i will pass ONLY one object.

This final line will print:

"My name is fred, i'm 25 years old"

Any idea of an actual api doing that?


Groovy, that is a Java language extension toward a ruby/python like language, allows you to easily embed variables inside strings:

String s = "Hello I'm a ${groovyname} string in which i can insert ${object.variable}"


You can do this using Spring Expression Langauge. Here is the code with example:

import org.springframework.expression.common.TemplateParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.ExpressionParser;

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

class Main {
    public static void main(String[] args) {
        Person p = new Person("abhinav", 24);
        String expression = "my name is #{name} and my age is #{age}";
        System.out.println(SpelFormatter.format(expression, p));
    }
}

class SpelFormatter {    
    private static final ExpressionParser PARSER = new SpelExpressionParser();
    private static final TemplateParserContext TEMPLATE_PARSER_CONTEXT = 
            new TemplateParserContext();    

    public static String format(String expression, Object context) {
        return PARSER.parseExpression(expression,
                TEMPLATE_PARSER_CONTEXT).getValue(context, String.class);
    }
}


Velocity is a Java-based template engine. It permits anyone to use a simple yet powerful template language to reference objects defined in Java code.

Check the User guide for syntax etc.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜