构造函数内的初始化块
我知道初始化块在构造函数中调用“super()”之后运行。然而,今天早上查看一些代码时,我发现了以下内容:
public class SimpleListLocalsAnalysis extends BackwardFlowAnalysis
FlowSet emptySet;
public SimpleLiveLocalsAnalysis(UnitGraph graph) {
super(graph);
{
Chain locals = g.getBody().getLocals();
FlowUniverse localUniverse = new FlowUniverse(locals.toArray());
emptySet = new ArrayPackedSet(localUniverse);
}
doAnalysis();
}
...
}
上面的代码显示了“super(graph)”调用之后初始化块内正在进行的一些初始化。将代码放在构造函数内的初始化块中的目的是什么,因为它肯定会在调用 super 之后运行。我在这里错过了什么吗?
I know that an initialization block runs after the call to 'super()' in a constructor. However, when looking through some code this morning, I found the following:
public class SimpleListLocalsAnalysis extends BackwardFlowAnalysis
FlowSet emptySet;
public SimpleLiveLocalsAnalysis(UnitGraph graph) {
super(graph);
{
Chain locals = g.getBody().getLocals();
FlowUniverse localUniverse = new FlowUniverse(locals.toArray());
emptySet = new ArrayPackedSet(localUniverse);
}
doAnalysis();
}
...
}
The above code shows some initialisation going on within an initialisation block just after 'super(graph)' invocation. What's the purpose of placing the code in an initialisation block within a constructor, as surely it runs anyway after the call to super. Am I missing something here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它不是初始化块,它的简单块
就像
目的:
你可以限制范围
Its not initilization block, its simple block
just like
Purpose:
You can have restricted scope
找出答案的最好方法可能是询问代码的作者。也许他包围了代码块以表明这些初始化的重要性。或者他这样做可能是因为他想表明
locals
和localUniverse
仅用于初始化emptySet
。另一方面,在 Java 中,您可以执行类似的操作,
初始化块将在编译时复制到每个构造函数的开头(在 super 调用之后)。
所以也许作者将代码块复制并粘贴到了错误的地方;他将其复制到构造函数中而不是构造函数外部。
The best way to find out is probably to ask the author of the code. Maybe he surrounded the block of code to indicate the importance of those initialization. Or maybe he did that because he wants to show that
locals
andlocalUniverse
are only used for initializingemptySet
.On the other hand, in Java you can do something like
The initialization block will get copy to the beginning of each of the constructors (after the super call) during compile time.
So maybe the author copy and pasted the block of code into wrong place; he copied it into the constructor instead of outside of the constructor.