这是一个bug,还是Groovy的人刻意做出的设计决定?
final String x = "a"
x = "b"你运行它,它将会工作,没有问题。难道不应该抛出运行时异常吗?用@CompileStatic注释这个类也没有什么帮助。当使用@CompileStatic时,我预计会出现编译错误。
发布于 2017-12-21 22:17:37
如果将其编译为Script,groovyc将忽略final关键字,但如果将其包装到类中,groovyc将引发编译错误。
带内容的fin.groovy
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了,如果你用content编译它
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 errorhttps://stackoverflow.com/questions/47926325
复制相似问题