字符串模板(STR."\{x}")曾经是预览特性,现在呢?这篇用 JDK 21 与 JDK 27 逐种写法真实编译,确认哪里能用、哪里已经不存在,再看字节码和处理器做了什么,以及不用它时的替代写法。
STR 基本插值
JDK 21:编译失败 string templates are a preview feature and are disabled by default.
JDK 21+预览:3 + 4 = 7
JDK 27:编译失败 illegal escape character
JDK 27+预览:编译失败 illegal escape character
表达式里调用方法与三元
JDK 21:编译失败 string templates are a preview feature and are disabled by default.
JDK 21+预览:f1 是
JDK 27:编译失败 illegal escape character
JDK 27+预览:编译失败 illegal escape character
多行文本块模板
JDK 21:编译失败 string templates are a preview feature and are disabled by default.
JDK 21+预览:hi tom | bye
JDK 27:编译失败 illegal escape character
JDK 27+预览:编译失败 illegal escape character
FMT 格式化模板
JDK 21:编译失败 string templates are a preview feature and are disabled by default.
JDK 21+预览:3.14 42
JDK 27:编译失败 illegal escape character
JDK 27+预览:编译失败 illegal escape character
RAW 与 StringTemplate 对象
JDK 21:编译失败 string templates are a preview feature and are disabled by default.
JDK 21+预览:[v=, ] [1] v=1
JDK 27:编译失败 illegal escape character
JDK 27+预览:编译失败 illegal escape character
自定义 Processor
JDK 21:编译失败 string templates are a preview feature and are disabled by default.
JDK 21+预览:HI TOM
JDK 27:编译失败 illegal escape character
JDK 27+预览:编译失败 illegal escape character String.format
JDK 21:3 + 4 = 7
JDK 21+预览:3 + 4 = 7
JDK 27:3 + 4 = 7
JDK 27+预览:3 + 4 = 7
formatted
JDK 21:3 + 4 = 7
JDK 21+预览:3 + 4 = 7
JDK 27:3 + 4 = 7
JDK 27+预览:3 + 4 = 7
MessageFormat
JDK 21:3 + 4
JDK 21+预览:3 + 4
JDK 27:3 + 4
JDK 27+预览:3 + 4
+ 拼接
JDK 21:3 + 4 = 7
JDK 21+预览:3 + 4 = 7
JDK 27:3 + 4 = 7
JDK 27+预览:3 + 4 = 7
文本块 formatted
JDK 21:hi tom | bye
JDK 21+预览:hi tom | bye
JDK 27:hi tom | bye
JDK 27+预览:hi tom | bye javap 里的关键行:
minor version: 65535
#31 = Utf8 BootstrapMethods
6: invokedynamic #13, 0 // InvokeDynamic #0:makeConcatWithConstants:(I)Ljava/lang/String;
BootstrapMethods:
JDK 21 预览运行: v=3!
JDK 21 不带 --enable-preview 运行: Error: LinkageError occurred while loading main class T
JDK 27 带 --enable-preview 运行 JDK 21 编出的类: Error: LinkageError occurred while loading main class T 编译: 0
运行输出:
select * from u where name = ? and age > ?
[x' OR '1'='1, 30]
select * from u where name = 'x' OR '1'='1'