这是Groovy的人们的错误还是故意的设计决定?
final String x = "a"
x = "b"
你运行它,它会工作,没问题。不应该抛出运行时异常吗?用@CompileStatic
注释班级也没有帮助。我在使用@CompileStatic
时期待编译错误。
答案 0 :(得分:4)
如果将其编译为Script
,groovyc
将忽略final
关键字,但如果将其包装到类中,groovyc
将引发编译错误
fin.groovy with content
final String x = "a"
x = "b"
$ groovyc fin.groovy
使用ByteCodeViewer
进行反编译import org.codehaus.groovy.reflection.*;
import java.lang.ref.*;
import groovy.lang.*;
import org.codehaus.groovy.runtime.*;
import org.codehaus.groovy.runtime.callsite.*;
public class fin extends Script
{
private static /* synthetic */ SoftReference $callSiteArray;
public fin() {
$getCallSiteArray();
}
public fin(final Binding context) {
$getCallSiteArray();
super(context);
}
public static void main(final String... args) {
$getCallSiteArray()[0].call((Object)InvokerHelper.class, (Object)fin.class, (Object)args);
}
public Object run() {
$getCallSiteArray();
String x = "a";
return x = "b";
}
private static /* synthetic */ CallSiteArray $createCallSiteArray() {
final String[] array = { null };
$createCallSiteArray_1(array);
return new CallSiteArray((Class)fin.class, array);
}
private static /* synthetic */ CallSite[] $getCallSiteArray() {
CallSiteArray $createCallSiteArray;
if (fin.$callSiteArray == null || ($createCallSiteArray = fin.$callSiteArray.get()) == null) {
$createCallSiteArray = $createCallSiteArray();
fin.$callSiteArray = new SoftReference($createCallSiteArray);
}
return $createCallSiteArray.array;
}
}
没有final
了,
如果你用内容编译它
class A{
final String x = "a"
def a(){
x = "b"
}
}
它给出了
$ groovyc fin.groovy
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
fin.groovy: 4: cannot modify final field 'x' outside of constructor.
@ line 4, column 3.
x = "b"
^
1 error