-
Notifications
You must be signed in to change notification settings - Fork 91
/
Copy pathStringTemplateCustomProcessorExample.java
48 lines (41 loc) · 1.33 KB
/
StringTemplateCustomProcessorExample.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* To run: `java --enable-preview --source 21 StringTemplateCustomProcessorExample.java`
*/
public class StringTemplateCustomProcessorExample {
public static void main(String[] args) {
usingClass();
usingLambda();
usingStaticFactoryMethod();
}
static void usingClass() {
class StringNullSanitizer implements StringTemplate.Processor<String, RuntimeException> {
public String process(StringTemplate st) {
return interpolate(st);
}
}
System.out.println(new StringNullSanitizer()."Test null: \{null}");
}
static void usingLambda() {
// lambda we must define the type
StringTemplate.Processor<String, RuntimeException> STR_NULL_SANITIZER = StringTemplateCustomProcessorExample::interpolate;
System.out.println(STR_NULL_SANITIZER."Test null: \{null}");
}
static void usingStaticFactoryMethod() {
var STR_NULL_SANITIZER = StringTemplate.Processor.of(StringTemplateCustomProcessorExample::interpolate);
System.out.println(STR_NULL_SANITIZER."Test null: \{null}");
}
static String interpolate(StringTemplate st) {
var sb = new StringBuilder();
var fragments = st.fragments().iterator();
for (Object value : st.values()) {
sb.append(fragments.next());
if (value == null) {
sb.append("<NULL>");
} else {
sb.append(value);
}
}
sb.append(fragments.next());
return sb.toString();
}
}