Java 中单独的 { code } 是做什么用的?
我最近读到一些关于 {}
使用特殊语法的代码,我询问了一位更有经验的 Java 开发人员,但他也无法回答。
public void doSomething() {
someWorks();
{
someVariables;
someMoreWorks();
}
someEvenWorks();
{
...
}
}
为什么代码作者将这些行放在 {}
中?我猜想 {}
中声明的变量将在执行退出 {}
后立即释放,对吧,因为我无法在 {} 外部访问这些变量
不再了吗?
I recently read some code that uses a special syntax regarding {}
, I've asked a more experienced Java developer, but he also can't answer.
public void doSomething() {
someWorks();
{
someVariables;
someMoreWorks();
}
someEvenWorks();
{
...
}
}
Why does the code author put these lines inside {}
? I guess that the variables declared within the {}
will be released right after execution exits {}
, right, because I can't access these outside the {}
anymore?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,唯一的区别是范围界定。
有时,这对于一次性代码很有用,例如微基准测试,您希望能够剪切和粘贴块并进行细微更改,然后可能对块重新排序。
不过,我很少(如果有的话)在“真实”代码中拥有类似的东西。
Yes, the only difference is for scoping.
Occasionally this can be useful for throwaway code such as micro-benchmarks where you want to be able to cut and paste a block and make a minor change, then potentially reorder the blocks.
I would rarely (if ever) have something like this in "real" code though.
这为他提供了一个嵌套范围来声明“更多本地”变量。
取决于您对“释放”的定义(在方法结束之前它们很可能不会被垃圾收集,因此如果这很重要,您可能希望将它们清空),但是是的。
大括号的其他罕见用途包括类和实例初始值设定项:
This gives him a nested scope to declare "more local" variables.
Depends on your definition of "release" (they will most likely not be garbage collected until the method ends, so if this is important, you might want to null them out), but yes.
Other rarely seen uses of curly brackets include class and instance initializers:
作者将这些变量放入 {} 中的事实表明这些变量的作用域仅是 {} 定义的方法的作用域;反过来,一旦方法完成执行,这些变量将被垃圾回收。
The fact that the author put those variables in {} indicates the scope of those variables will only be that of the method defined by the {}; in turn, those variables will be up for garbage collection once method finishes execution.