是的,有可能,您可以在任何可以使用单独声明的地方使用块.在该块内声明的变量仅在块内有效.例如.:
void method() {
String allThisCodeCanSeeMe;
// ...
{
String onlyThisBlockCanSeeMe;
// ...
}
{
String onlyThisSecondBlockCanSeeMe;
// ...
}
// ....
}
但是:通常,如果你发现自己想要做这样的事情,它表明你需要将代码分解为更小的函数/方法,并且当前你的一个方法调用那些较小的部分:
void method() {
String thisMethodCanSeeMe;
// ...
this.aSmallerMethod(); // <== Can pass in `thisMethodCanSeeMe`
this.anotherSmallerMethod(); // <== if needed
// ...
}
private void aSmallerMethod() {
String onlyThisMethodCanSeeMe;
// ...
}
private void anotherSmallerMethod() {
String onlyThisSecondSmallerMethodCanSeeMe;
// ...
}