Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I recently discovered <a href="http://juel.sourceforge.net/" rel="nofollow">JUEL</a> which fits the description nicely. It is the expression language taken out of JSP. It claims to be very fast, too.</p> <p>I'm about to try it out in one of my own projects.</p> <p>But for a lighter-weight, which is a variant of yours, try this (wrapped in a unit test):</p> <pre><code>public class TestInterpolation { public static class NamedFormatter { public final static Pattern pattern = Pattern.compile("#\\{(?&lt;key&gt;.*)}"); public static String format(final String format, Map&lt;String, ? extends Object&gt; kvs) { final StringBuffer buffer = new StringBuffer(); final Matcher match = pattern.matcher(format); while (match.find()) { final String key = match.group("key"); final Object value = kvs.get(key); if (value != null) match.appendReplacement(buffer, value.toString()); else if (kvs.containsKey(key)) match.appendReplacement(buffer, "null"); else match.appendReplacement(buffer, ""); } match.appendTail(buffer); return buffer.toString(); } } @Test public void test() { assertEquals("hello world", NamedFormatter.format("hello #{name}", map("name", "world"))); assertEquals("hello null", NamedFormatter.format("hello #{name}", map("name", null))); assertEquals("hello ", NamedFormatter.format("hello #{name}", new HashMap&lt;String, Object&gt;())); } private Map&lt;String, Object&gt; map(final String key, final Object value) { final Map&lt;String, Object&gt; kvs = new HashMap&lt;&gt;(); kvs.put(key, value); return kvs; } } </code></pre> <p>I'd extend it to add convenience methods to for quick key-value pairs</p> <pre><code>format(format, key1, value1) format(format, key1, value1, key2, value2) format(format, key1, value1, key2, value2, key3, value3) ... </code></pre> <p>And it shouldn't be too hard to convert from java 7+ to java 6-</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload