在Java中将变量范围扩展到花括号之外 [英] Expanding variable scope beyond curly braces in Java

查看:239
本文介绍了在Java中将变量范围扩展到花括号之外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下代码块:

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

其目的是获取某个对象foo的版本和内容的线程安全一致视图.

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?

(注意:我不想只是将// Do something with version and content拉入同步块中.)

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

推荐答案

简单地说...不.作用域变量仅在声明的作用域中可用.这就是他们的重点.在 Java语言规范:

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:

块(第14.2节)中局部变量声明的范围是 声明出现的块的其余部分,从其开始 自己的初始化程序(第14.4节),并包括 在局部变量声明语句中.

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).

这篇关于在Java中将变量范围扩展到花括号之外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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