|
| 1 | +package com.ibrahimatay; |
| 2 | + |
| 3 | + |
| 4 | +import static java.lang.StringTemplate.RAW; |
| 5 | +import static java.lang.StringTemplate.STR; |
| 6 | +import static java.util.FormatProcessor.FMT; |
| 7 | + |
| 8 | +/* |
| 9 | +* JEP 430: String Templates (Preview) |
| 10 | +* https://openjdk.org/jeps/430 |
| 11 | +* */ |
| 12 | +public class JEP430StringTemplates { |
| 13 | + |
| 14 | + public static void main(String[] args) { |
| 15 | + System.out.println(interpolationUsingSTRProcessor(getFeelsLike(), getTemperature(), getUnit())); |
| 16 | + System.out.println(interpolationOfJSONBlock(getFeelsLike(), getTemperature(), getUnit())); |
| 17 | + System.out.println(interpolationWithExpressions()); |
| 18 | + System.out.println(interpolationWithTemplates()); |
| 19 | + System.out.println(interpolationOfJSONBlockWithFMT(getFeelsLike(), 25, getUnit())); |
| 20 | + } |
| 21 | + |
| 22 | + static String interpolationUsingSTRProcessor(String feelsLike, String temperature, String unit) { |
| 23 | + return STR |
| 24 | + . "Today's weather is \{ feelsLike }, with a temperature of \{ temperature } degrees \{ unit }" ; |
| 25 | + } |
| 26 | + |
| 27 | + static String interpolationOfJSONBlock(String feelsLike, String temperature, String unit) { |
| 28 | + return STR |
| 29 | + . """ |
| 30 | + { |
| 31 | + "feelsLike": "\{ feelsLike }", |
| 32 | + "temperature": "\{ temperature }", |
| 33 | + "unit": "\{ unit }" |
| 34 | + } |
| 35 | + """ ; |
| 36 | + } |
| 37 | + |
| 38 | + static String interpolationWithExpressions() { |
| 39 | + return STR |
| 40 | + . "Today's weather is \{ getFeelsLike() }, with a temperature of \{ getTemperature() } degrees \{ getUnit() }" ; |
| 41 | + } |
| 42 | + |
| 43 | + static String interpolationWithTemplates() { |
| 44 | + StringTemplate str = RAW |
| 45 | + . "Today's weather is \{ getFeelsLike() }, with a temperature of \{ getTemperature() } degrees \{ getUnit() }" ; |
| 46 | + return STR.process(str); |
| 47 | + } |
| 48 | + |
| 49 | + static String interpolationOfJSONBlockWithFMT(String feelsLike, float temperature, String unit) { |
| 50 | + return FMT |
| 51 | + . """ |
| 52 | + { |
| 53 | + "feelsLike": "%1s\{ feelsLike }", |
| 54 | + "temperature": "%2.2f\{ temperature }", |
| 55 | + "unit": "%1s\{ unit }" |
| 56 | + } |
| 57 | + """ ; |
| 58 | + } |
| 59 | + |
| 60 | + private static String getFeelsLike() { |
| 61 | + return "pleasant"; |
| 62 | + } |
| 63 | + |
| 64 | + private static String getTemperature() { |
| 65 | + return "25"; |
| 66 | + } |
| 67 | + |
| 68 | + private static String getUnit() { |
| 69 | + return "Celsius"; |
| 70 | + } |
| 71 | +} |
0 commit comments