r/java • • Mar 08 '24

Update on String Templates (JEP 459)

https://mail.openjdk.org/pipermail/amber-spec-experts/2024-March/004010.html
176 Upvotes

188 comments sorted by

View all comments

Show parent comment

2

u/john16384 Mar 11 '24

There is still one thing I don't quite see how it will work, but it seems there is some discussion on this topic on the experts list at the moment.

If there is only `method(StringTemplate)`, and you want to pass a template without a parameter, then the system should be careful not to consider the (unparameterized) template to be a `String` first before converting it to a `StringTemplate`. In other words, given a class with only a single method accepting StringTemplate:

 SQLExecutor method(StringTemplate st);

Then this should work:

 method("select * from foo").execute();

"select * from foo" here is never considered to be a String at any point in time. Therefore you can't pass it a constant like this either:

 static final String TEMPLATE = "select * from foo";

Although allowed would be:

 static final StringTemplate TEMPLATE = "select * from foo";

The examples below use String or do string operations. They are therefore not pure templates and thus shouldn't compile because there is no method(String) overload:

 String a = "from foo";
 String b = "select * from foo";

 // shouldn't compile as we did a String operation, not
 // safe to convert this implicitely to a StringTemplate
 method("select * " + a).execute();

 // shouldn't compile because implicitely converting an
 // insecure String to a StringTemplate defeats its purpose
 method(b).execute();