mada
mada

Reputation: 1565

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.println(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?

Upvotes: 3

Views: 865

Answers (3)

Abhinav Sarkar
Abhinav Sarkar

Reputation: 23802

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);
    }
}

Upvotes: 2

Jack
Jack

Reputation: 133569

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}"

Upvotes: 2

stacker
stacker

Reputation: 68972

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.

Upvotes: 0

Related Questions