简体   繁体   English

在Java中扩展变量范围超出花括号

[英]Expanding variable scope beyond curly braces in Java

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. 它的目的是获取一些对象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.) (注:我不想简单地拉// Do something with version and content 。到synchronized块)

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 : 这在Java语言规范的第14.4.2节中描述

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. 块(第14.2节)中局部变量声明的范围是声明出现的块的其余部分,从其自己的初始化器(第14.4节)开始,并在本地变量声明语句中包含右侧的任何其他声明器。

Your variables need to be declared in the scope they are to be used in (or higher, but definitely not lower). 您的变量需要在它们要使用的范围内声明(或更高,但绝对不低)。

Unfortunately, no. 抱歉不行。 It's just something that looks better/normal as you use the language more and more. 当你越来越多地使用这种语言时,这只是看起来更好/更正常的东西。

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM