Java中的匿名代码块 [英] Anonymous code blocks in Java

查看:140
本文介绍了Java中的匿名代码块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java中是否存在匿名代码块的实际用途?

Are there any practical uses of anonymous code blocks in Java?

public static void main(String[] args) {
    // in
    {
        // out
    }
}

请注意,这不是关于命名的块,即

Please note that this is not about named blocks, i.e.

name: { 
     if ( /* something */ ) 
         break name;
}

推荐答案

他们限制变量范围。

public void foo()
{
    {
        int i = 10;
    }
    System.out.println(i); // Won't compile.
}

但实际上,如果你发现自己使用了这样的代码块一个标志,您想要将该块重构为方法。

In practice, though, if you find yourself using such a code block that's probably a sign that you want to refactor that block out to a method.

这篇关于Java中的匿名代码块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆