java 大括号之外的小括号,在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.

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

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值