StringTemplate is a preview API of the Java platform.StringTemplate when preview features are enabled.StringTemplatePREVIEW is the run-time representation of a string template or text block template in a template expression. In the source code of a Java program, a string template or text block template contains an interleaved succession offragment literals andembedded expressions. Thefragments() method returns the fragment literals, and thevalues() method returns the results of evaluating the embedded expressions.StringTemplatePREVIEW does not provide access to the source code of the embedded expressions themselves; it is not a compile-time representation of a string template or text block template.
StringTemplatePREVIEW is primarily used in conjunction with a template processor to produce a string or other meaningful value. Evaluation of a template expression first produces an instance ofStringTemplatePREVIEW, representing the right hand side of the template expression, and then passes the instance to the template processor given by the template expression.
For example, the following code contains a template expression that uses the template processorRAW, which simply yields theStringTemplatePREVIEW passed to it:
int x = 10;int y = 20;StringTemplate st = RAW."\{x} + \{y} = \{x + y}";List<String> fragments = st.fragments();List<Object> values = st.values();fragments will be equivalent toList.of("", " + ", " = ", ""), which includes the empty first and last fragments.values will be the equivalent ofList.of(10, 20, 30). The following code contains a template expression with the same template but with a different template processor,STR:
int x = 10;int y = 20;String s = STR."\{x} + \{y} = \{x + y}";StringTemplatePREVIEW is produced that returns the same lists fromfragments() andvalues() as shown above. TheSTR template processor uses these lists to yield an interpolated string. The value ofs will be equivalent to"10 + 20 = 30". Theinterpolate() method provides a direct way to perform string interpolation of aStringTemplatePREVIEW. Template processors can use the following code pattern:
List<String> fragments = st.fragments();List<Object> values = st.values();... check or manipulate the fragments and/or values ...String result = StringTemplate.interpolate(fragments, values);process(Processor) method, in conjunction with theRAW processor, may be used to defer processing of aStringTemplatePREVIEW.StringTemplate st = RAW."\{x} + \{y} = \{x + y}";...other steps...String result = st.process(STR);of(String) andof(List, List) can be used to construct aStringTemplatePREVIEW.- Implementation Note:
- Implementations of
StringTemplatePREVIEW must minimally implement the methodsfragments()andvalues(). Instances ofStringTemplatePREVIEW are considered immutable. To preserve the semantics of string templates and text block templates, the list returned byfragments()must be one element larger than the list returned byvalues(). - SeeJava Language Specification:
- 15.8.6 Process Template Expressions
- Since:
- 21
- See Also:
Nested Class Summary
Nested ClassesModifier and TypeInterfaceDescriptionstatic interfaceStringTemplate.ProcessorPREVIEW<R,E extendsThrowable> Preview.This interface describes the methods provided by a generalized string template processor.Field Summary
FieldsModifier and TypeFieldDescriptionThisStringTemplate.ProcessorPREVIEW instance is conventionally used to indicate that the processing of theStringTemplatePREVIEW is to be deferred to a later time.static finalStringTemplate.ProcessorPREVIEW<String, RuntimeException> ThisStringTemplate.ProcessorPREVIEW instance is conventionally used for the string interpolation of a suppliedStringTemplatePREVIEW.Method Summary
Modifier and TypeMethodDescriptionstaticStringTemplatePREVIEWcombine(StringTemplatePREVIEW... stringTemplates) staticStringTemplatePREVIEWcombine(List<StringTemplatePREVIEW> stringTemplates) Returns a list of fragment literals for thisStringTemplatePREVIEW.defaultStringReturns the string interpolation of the fragments and values for thisStringTemplatePREVIEW.staticStringinterpolate(List<String> fragments,List<?> values) Creates a string that interleaves the elements of values between the elements of fragments.staticStringTemplatePREVIEWReturns aStringTemplatePREVIEW as if constructed by invokingStringTemplate.of(List.of(string), List.of()).staticStringTemplatePREVIEWReturns a StringTemplate with the given fragments and values.default <R,E extendsThrowable>
Rprocess(StringTemplate.ProcessorPREVIEW<? extends R, ? extends E> processor) Returns the result of applying the specified processor to thisStringTemplatePREVIEW.staticStringtoString(StringTemplatePREVIEW stringTemplate) Produces a diagnostic string that describes the fragments and values of the suppliedStringTemplatePREVIEW.values()Returns a list of embedded expression results for thisStringTemplatePREVIEW.
Field Details
STR
ThisStringTemplate.ProcessorPREVIEW instance is conventionally used for the string interpolation of a suppliedStringTemplatePREVIEW.For better visibility and when practical, it is recommended that users use the
STRprocessor instead of invoking theinterpolate()method. Example:In the above example, the value ofint x = 10;int y = 20;String result =STR."\{x} + \{y} = \{x + y}";resultwill be"10 + 20 = 30". This is produced by the interleaving concatenation of fragments and values from the suppliedStringTemplatePREVIEW. To accommodate concatenation, values are converted to strings as if invokingString.valueOf(Object).- API Note:
STRis statically imported implicitly into every Java compilation unit.
RAW
ThisStringTemplate.ProcessorPREVIEW instance is conventionally used to indicate that the processing of theStringTemplatePREVIEW is to be deferred to a later time. Deferred processing can be resumed by invoking theprocess(Processor)orStringTemplate.Processor.process(StringTemplate)PREVIEW methods.import static java.lang.StringTemplate.RAW;...StringTemplate st = RAW."\{x} + \{y} = \{x + y}";...other steps...String result = STR.process(st);
Method Details
fragments
Returns a list of fragment literals for thisStringTemplatePREVIEW. The fragment literals are the character sequences preceding each of the embedded expressions in source code, plus the character sequence following the last embedded expression. Such character sequences may be zero-length if an embedded expression appears at the beginning or end of a template, or if two embedded expressions are directly adjacent in a template. In the example:String student = "Mary";String teacher = "Johnson";StringTemplate st = RAW."The student \{student} is in \{teacher}'s classroom.";List<String> fragments = st.fragments();fragmentswill be equivalent toList.of("The student ", " is in ", "'s classroom.")- Implementation Requirements:
- the list returned is immutable
- Returns:
- list of string fragments
values
Returns a list of embedded expression results for thisStringTemplatePREVIEW. In the example:String student = "Mary";String teacher = "Johnson";StringTemplate st = RAW."The student \{student} is in \{teacher}'s classroom.";List<Object> values = st.values();valueswill be equivalent toList.of(student, teacher)- Implementation Requirements:
- the list returned is immutable
- Returns:
- list of expression values
interpolate
Returns the string interpolation of the fragments and values for thisStringTemplatePREVIEW.- API Note:
- For better visibility and when practical, it is recommended to use the
STRprocessor instead of invoking theinterpolate()method.In the above example, the value ofString student = "Mary";String teacher = "Johnson";StringTemplate st = RAW."The student \{student} is in \{teacher}'s classroom.";String result = st.interpolate();resultwill be"The student Mary is in Johnson's classroom.". This is produced by the interleaving concatenation of fragments and values from the suppliedStringTemplatePREVIEW. To accommodate concatenation, values are converted to strings as if invokingString.valueOf(Object). - Implementation Requirements:
- The default implementation returns the result of invoking
StringTemplate.interpolate(this.fragments(), this.values()). - Returns:
- interpolation of this
StringTemplatePREVIEW
process
default <R,E extendsThrowable> R process(StringTemplate.ProcessorPREVIEW<? extends R, ? extends E> processor) throwsEReturns the result of applying the specified processor to thisStringTemplatePREVIEW. This method can be used as an alternative to string template expressions. For example,Produces an equivalent result for bothString student = "Mary";String teacher = "Johnson";String result1 = STR."The student \{student} is in \{teacher}'s classroom.";String result2 = RAW."The student \{student} is in \{teacher}'s classroom.".process(STR);result1andresult2.- Implementation Requirements:
- The default implementation returns the result of invoking
processor.process(this). If the invocation throws an exception that exception is forwarded to the caller. - Type Parameters:
R- Processor's process result type.E- Exception thrown type.- Parameters:
processor- theStringTemplate.ProcessorPREVIEW instance to process- Returns:
- constructed object of type
R - Throws:
E- exception thrown by the template processor when validation failsNullPointerException- if processor is null
toString
Produces a diagnostic string that describes the fragments and values of the suppliedStringTemplatePREVIEW.- Parameters:
stringTemplate- theStringTemplatePREVIEW to represent- Returns:
- diagnostic string representing the supplied string template
- Throws:
NullPointerException- if stringTemplate is null
of
Returns aStringTemplatePREVIEW as if constructed by invokingStringTemplate.of(List.of(string), List.of()). That is, aStringTemplatePREVIEW with one fragment and no values.- Parameters:
string- single string fragment- Returns:
- StringTemplate composed from string
- Throws:
NullPointerException- if string is null
of
Returns a StringTemplate with the given fragments and values.- Implementation Requirements:
- The
fragmentslist size must be one more that thevalueslist size. - Implementation Note:
- Contents of both lists are copied to construct immutable lists.
- Parameters:
fragments- list of string fragmentsvalues- list of expression values- Returns:
- StringTemplate composed from string
- Throws:
IllegalArgumentException- if fragments list size is not one more than values list sizeNullPointerException- if fragments is null or values is null or if any fragment is null.
interpolate
Creates a string that interleaves the elements of values between the elements of fragments. To accommodate interpolation, values are converted to strings as if invokingString.valueOf(Object).- Parameters:
fragments- list of String fragmentsvalues- list of expression values- Returns:
- String interpolation of fragments and values
- Throws:
IllegalArgumentException- if fragments list size is not one more than values list sizeNullPointerException- fragments or values is null or if any of the fragments is null
combine
Combine zero or moreStringTemplatesPREVIEW into a singleStringTemplatePREVIEW.Fragment lists from theStringTemplate st = StringTemplate.combine(RAW."\{a}", RAW."\{b}", RAW."\{c}");assert st.interpolate().equals(STR."\{a}\{b}\{c}");StringTemplatesPREVIEW are combined end to end with the last fragment from eachStringTemplatePREVIEW concatenated with the first fragment of the next. To demonstrate, if we were to take two strings and we combined them as follows:the last characterString s1 = "abc";String s2 = "xyz";String sc = s1 + s2;assert Objects.equals(sc, "abcxyz");"c"from the first string is juxtaposed with the first character"x"of the second string. The same would be true of combiningStringTemplatesPREVIEW.Values lists are simply concatenated to produce a single values list. The result is a well-formedStringTemplate st1 = RAW."a\{}b\{}c";StringTemplate st2 = RAW."x\{}y\{}z";StringTemplate st3 = RAW."a\{}b\{}cx\{}y\{}z";StringTemplate stc = StringTemplate.combine(st1, st2);assert Objects.equals(st1.fragments(), List.of("a", "b", "c"));assert Objects.equals(st2.fragments(), List.of("x", "y", "z"));assert Objects.equals(st3.fragments(), List.of("a", "b", "cx", "y", "z"));assert Objects.equals(stc.fragments(), List.of("a", "b", "cx", "y", "z"));StringTemplatePREVIEW with n+1 fragments and n values, where n is the total of number of values across all the suppliedStringTemplatesPREVIEW.- Implementation Note:
- If zero
StringTemplatePREVIEW arguments are provided then aStringTemplatePREVIEW with an empty fragment and no values is returned, as if invokingStringTemplate.of(""). If only oneStringTemplatePREVIEW argument is provided then it is returned unchanged. - Parameters:
stringTemplates- zero or moreStringTemplatePREVIEW- Returns:
- combined
StringTemplatePREVIEW - Throws:
NullPointerException- if stringTemplates is null or if any of thestringTemplatesare null
combine
Combine a list ofStringTemplatesPREVIEW into a singleStringTemplatePREVIEW.Fragment lists from theStringTemplate st = StringTemplate.combine(List.of(RAW."\{a}", RAW."\{b}", RAW."\{c}"));assert st.interpolate().equals(STR."\{a}\{b}\{c}");StringTemplatesPREVIEW are combined end to end with the last fragment from eachStringTemplatePREVIEW concatenated with the first fragment of the next. To demonstrate, if we were to take two strings and we combined them as follows:the last characterString s1 = "abc";String s2 = "xyz";String sc = s1 + s2;assert Objects.equals(sc, "abcxyz");"c"from the first string is juxtaposed with the first character"x"of the second string. The same would be true of combiningStringTemplatesPREVIEW.Values lists are simply concatenated to produce a single values list. The result is a well-formedStringTemplate st1 = RAW."a\{}b\{}c";StringTemplate st2 = RAW."x\{}y\{}z";StringTemplate st3 = RAW."a\{}b\{}cx\{}y\{}z";StringTemplate stc = StringTemplate.combine(List.of(st1, st2));assert Objects.equals(st1.fragments(), List.of("a", "b", "c"));assert Objects.equals(st2.fragments(), List.of("x", "y", "z"));assert Objects.equals(st3.fragments(), List.of("a", "b", "cx", "y", "z"));assert Objects.equals(stc.fragments(), List.of("a", "b", "cx", "y", "z"));StringTemplatePREVIEW with n+1 fragments and n values, where n is the total of number of values across all the suppliedStringTemplatesPREVIEW.- Implementation Note:
- If
stringTemplates.size() == 0then aStringTemplatePREVIEW with an empty fragment and no values is returned, as if invokingStringTemplate.of(""). IfstringTemplates.size() == 1then the first element of the list is returned unchanged. - Parameters:
stringTemplates- list ofStringTemplatePREVIEW- Returns:
- combined
StringTemplatePREVIEW - Throws:
NullPointerException- if stringTemplates is null or if any of the its elements are null