(My other answer is probably useful if you are already using struts.)
Similar to sdb answer, apache JEXL .
The UnifiedJEXL class provides UnifiedJEXL functionality, so you can write ( as shown in javadocs ):
JexlEngine jexl = new JexlEngine(); UnifiedJEXL ujexl = new UnifiedJEXL(jexl); UnifiedJEXL.Expression expr = ujexl.parse("Hello ${user}"); String hello = expr.evaluate(context, expr).toString();
( expr not only looks strange, is passed as a parameter to the method itself, but is not really needed as a parameter)
The context setting is shown earlier on the same page:
// Create a context and add data JexlContext jc = new MapContext(); jc.set("foo", new Foo() );
You will also need either a Commons entry, or you can configure JEXL to use your own registrar.
So, to get closer to what you requested, you can create:
public class Formatter { public static String format(String format, Object ... inputs) { JexlContext context = new MapContext(); for (int i=0;i<inputs.length;i++) { context.set("_" + (i+1), inputs[i] ); } JexlEngine jexl = new JexlEngine(); UnifiedJEXL ujexl = new UnifiedJEXL(jexl); UnifiedJEXL.Expression expr = ujexl.parse(format); return expr.evaluate(context).toString(); } }
and name him
String someString = "Your value is ${_1.myValue}."; String result = Formatter.format(someString, new MyClass());
At this point, result is "Your value is foo."