假设我们有:
final JList list = new JList(buffer.toArray());
我想这样声明一个 JList,但是我从 SQL 查询中获取缓冲区变量,因此,在 try 循环中。有什么方法可以使用在其中的 try/catch 之外声明的变量?
假设我们有:
final JList list = new JList(buffer.toArray());
我想这样声明一个 JList,但是我从 SQL 查询中获取缓冲区变量,因此,在 try 循环中。有什么方法可以使用在其中的 try/catch 之外声明的变量?
再次,正如我在您的另一个线程中指出的那样,在循环或块之前声明它。
通过在 try 块之外声明变量,如下所示:
JList list = null;
try {
list = new JList(buffer.toArray());
} catch (SomeNastyException eekwhatthebleepwentwrong) {
// at least print some info about the exception
}
我想这可能是你所追求的:
JList list = null;
try {
...
list = new JList(buffer.toArray());
final JList finalist = list;
... instantiate anonymous class that refers to finalist
} finally {
if (list != null) {
....
}
}
或者如果final
try/catch/finally ...
JList list = null;
try {
...
list = new JList(buffer.toArray());
} finally {
if (list != null) {
....
}
}
final JList finalist = list;
唯一在final
这里使事情稍微复杂化,但是创建具有与非决赛相同值的本地决赛的“技巧”足以处理它。
(如果final
出于这个原因不需要修饰符,请摆脱它。它只会引起问题。)