Expanding variable scope beyond curly braces in Java

99封情书 提交于 2019-12-23 05:21:02

问题


Let's say I have the following code block:

int    version;
String content;
synchronized (foo) {
    version = foo.getVersion();
    content = foo.getContent();
}
// Do something with version and content

Its purpose is to grab a thread-safe consistent view of the version and content of some object foo.

Is there a way to write it more concisely to look more like this?

synchronized (foo) {
    int    version = foo.getVersion();
    String content = foo.getContent();
}
// Do something with version and content

The problem is that in this version the variables are defined in the scope of the (synchronized) curly braces and can therefore not be accessed outside of the block. So, the question is: Is there some way to mark these curly braces as not defining a new scope block or marking the variables as belonging to the parent scope without having to declare them there?

(Note: I do not want to simply pull the // Do something with version and content into the synchronized block.)


回答1:


Simply put ... no. Scoped variables are only available in the scope they are declared. Thats their whole point. This is described in section 14.4.2 of the Java Language Specification:

The scope of a local variable declaration in a block (§14.2) is the rest of the block in which the declaration appears, starting with its own initializer (§14.4) and including any further declarators to the right in the local variable declaration statement.

Your variables need to be declared in the scope they are to be used in (or higher, but definitely not lower).




回答2:


Unfortunately, no. It's just something that looks better/normal as you use the language more and more.




回答3:


If you want these variables not to be accessible from other scope, you may define both, the variables and the synchronized block in another scope. Something like this:

{
    int    version;
    String content;
    synchronized (foo) {
        version = foo.getVersion();
        content = foo.getContent();
    }
    // Do something with version and content
}


来源:https://stackoverflow.com/questions/14793901/expanding-variable-scope-beyond-curly-braces-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!