以下代码输出令人惊讶的值 51
int a = "3"
println a // outputs 51
Run Code Online (Sandbox Code Playgroud)
Groovy似乎将这个3角色解释为int并继承.
为什么groovy不扔ClassCastException?如何阻止groovy忽略这些类型的打字错误?
的int a = "3"用途Groovy的类型强制和自动转换为"3"到char并将其转换成的51的ASCII整数值仅表现得像这对于单个位数的字符串(两个或更多个数字将生成运行时错误).此声明与结果相同int a = (char)"3".这种类型的无声bug可能很讨厌,但类型检查可以检测到这样的错误.
在Groovy中,您可以在类或方法级别启用静态类型检查.
@groovy.transform.TypeChecked
void run1() {
int a = "3" // triggers type-check exception
println a
}
@groovy.transform.TypeChecked
void run2() {
def a = '3' as int
println a // outputs 3
}
run1()
run2()
Run Code Online (Sandbox Code Playgroud)
静态类型检查强制执行严格的编译时类型检查.
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
C:\java\groovy\Example.groovy: 3: [Static type checking]
- Cannot assign value of type java.lang.String to variable of type int
@ line 3, column 10.
int a = "3" // triggers type-check exception
^
Run Code Online (Sandbox Code Playgroud)