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

查看:26
本文介绍了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;
}

.

推荐答案

它们限制了变量作用域.

They restrict variable scope.

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天全站免登陆