RFE: StringTemplate interpolation with custom function

Jim Laskey james.laskey at oracle.com
Thu Oct 26 20:05:37 UTC 2023


I think I’m missing something. Why wouldn’t you just;

import java.lang.StringTemplate.Processor;

Processor<URL, RuntimeException> urlEncode = template -> URLEncoder.encode(template.interpolate(), UTF_8));

Processor<String, RuntimeException> CSV = template -> StringEscapeUtils.escapeCsv<https://commons.apache.org/proper/commons-lang/apidocs/src-html/org/apache/commons/lang3/StringEscapeUtils.html#line.768>(template.interpolate());


On Oct 26, 2023, at 4:47 PM, Rob Spoor <openjdk at icemanx.nl> wrote:

I've been reading up on string templates, and I think it's a very cool feature. However, writing a custom processor can be a lot of copy-paste work if you want STR but with some extra translation applied. For instance, if I'd want to have a URL encoding processor I would have to write everything from scratch.

I think it would be useful to overload interpolate (both static and non-static) with a custom Function<Object, String> as additional arguments. This would work like STR if that provided String::valueOf as function.

With this method, creating a URL encoding processor would be as simple as this:

   var urlEncode = template -> template.interpolate(o ->
           URLEncoder.encode(String.valueOf(o), UTF_8));

   var url = urlEncode."https://host/path/\{id}?param=\{value\}";


Likewise, a processor backed by Apache Commons Text's StringEscapeUtils would now be just as simple:

   var CSV = template -> template.interpolate(o ->
           StringEscapeUtils.ESCAPE_CSV.translate(String.valueOf(o));

   var csv = CSV."""
           Header1, Header2, Header3
           "\{value1}", "\{value2}", "\{value3}"
           """;


If the JVM allows it, the existing interpolate method can even delegate to the new overload providing String::valueOf.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/core-libs-dev/attachments/20231026/f83b89aa/attachment-0001.htm>


More information about the core-libs-dev mailing list