Java 中的方法中是否使用了自由浮动块? [英] Is there a use of free floating block inside a method in Java?

查看:11
本文介绍了Java 中的方法中是否使用了自由浮动块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道方法可以有这样的浮动块:

I didn't know methods could have floating blocks like this:

class X { 
    public static void main( String [] args ) {
        { //<--- start
            int i;
        } //<-- ends
    }
}

我知道方法外有浮动块,但从未在方法内尝试过.

I was aware of floating blocks outside methods, but never tried them inside.

这可能用于定义本地范围或其他内容.

This could probably be used to define local scope or something.

Java 中的方法内部是否可以使用浮动块?

Is there a use for floating blocks inside methods in Java?

推荐答案

有用吗?

是 - 限制局部变量的范围.

Yes - to limit the scope of local variables.

这是个好主意吗?

可能有争议(并且可能会).

Probably debatable (and likely will be).

专业"阵营会说缩小变量的范围永远不会有什么坏处.con"阵营会说,如果你在一个方法中使用它并且你的方法足够长以保证将变量的范围缩小到特定的部分,那么这可能表明你应该从不同的部分中制作单独的方法.

The "pro" camp will say it never hurts to narrow the scope of variable. The "con" camp will say that, if you use it in a method and your method is long enough to warrant narrowing the scope of variables to specific sections, then it is probably an indication that you should make separate methods out of the different sections.

就个人而言,我使用它们,例如:

Personally, I use them, e.g.:

public void doGet(
        final HttpServletRequest request,
        final HttpServletResponse response)
  throws IOException {
    final PersistenceManager pm = PMF.get().getPersistenceManager();

    final List<ToDoListGaejdo> toDoLists;
    {
        final Query query = pm.newQuery(ToDoListGaejdo.class);
        query.setOrdering("listName asc");
        toDoLists = (List<ToDoListGaejdo>) query.execute();
    }

    final List<ToDoItemGaejdo> entries;
    {
        final Query query = pm.newQuery(ToDoItemGaejdo.class);
        query.setOrdering("listName asc, priority asc");
        entries = (List<ToDoItemGaejdo>) query.execute();
    }

    final ServletOutputStream out = response.getOutputStream();

    out.println("<head>");
    out.println("  <title>Debug View</title>");
    ....

这篇关于Java 中的方法中是否使用了自由浮动块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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