Advance MessageFormat with Introspection

I am looking for the following function described below. The MessageFormat sun api does not meet my need, and the Spring El expression may also be.

Assuming we have an Object named:

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 translation method, I will transfer ONLY one object.

This final line will print:

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

Any idea of โ€‹โ€‹the actual api doing this?

+3
source share
3 answers

Groovy , that is, the extension of the Java language in the ruby โ€‹โ€‹/ python language, makes it easy to insert variables inside strings:

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

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

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);
    }
}
+2
source

Velocity - Java. , , Java-.

..

0
source

Source: https://habr.com/ru/post/1751607/


All Articles