What do curly braces in Java mean by themselves?

2019-01-04 23:47发布

I have some Java code that uses curly braces in two ways

// Curly braces attached to an 'if' statement:
if(node.getId() != null)
{
    node.getId().apply(this);
}

// Curly braces by themselves:
{
    List<PExp> copy = new ArrayList<PExp>(node.getArgs());
    for(PExp e : copy)
    {
        e.apply(this);
    }
}
outAMethodExp(node);

What do those stand-alone curly braces after the first if statement mean?

11条回答
在下西门庆
2楼-- · 2019-01-05 00:28

As an interesting note: the braces actually enable a class of statements: declarations.

This is illegal: if(a) int f;

but this is legal: if(a) { int f; }

查看更多
Root(大扎)
3楼-- · 2019-01-05 00:30

They define a new scope which means that everything declared in this scope is not visible outside the curly braces.

查看更多
Rolldiameter
4楼-- · 2019-01-05 00:31

The only purpose of the extra braces is to provide scope-limit. The List<PExp> copy will only exist within those braces, and will have no scope outside of them.

If this is generated code, I assume the code-generator does this so it can insert some code (such as this) without having to worry about how many times it has inserted a List<PExp> copy and without having to worry about possibly renaming the variables if this snippet is inserted into the same method more than once.

查看更多
Summer. ? 凉城
5楼-- · 2019-01-05 00:41

I second what matt b wrote, and I'll add that another use I've seen of anonymous braces is to declare an implicit constructor in anonymous classes. For example:

  List<String> names = new ArrayList<String>() {
    // I want to initialize this ArrayList instace in-line,
    // but I can't define a constructor for an anonymous class:
      {
        add("Adam");
        add("Eve");
      }

  };

Some unit-testing frameworks have taken this syntax to another level, which does allow some slick things which look totally uncompilable to work. Since they look unfamiliar, I am not such a big fan myself, but it is worthwhile to at least recognize what is going on if you run across this use.

查看更多
爱情/是我丢掉的垃圾
6楼-- · 2019-01-05 00:41

I think they just define an unnamed level of scope.

查看更多
登录 后发表回答