我想使用try-with-resources。我有两个资源,第二个资源首先依赖。首先初始化之后,我需要在第一个资源上执行方法。接下来,我可以初始化第二个资源。我该怎么办?
try (First first = resource.get());
--Here I need run method: first.connect(...);
Second second = first.get())
{
...
}
答案 0 :(得分:2)
您可以嵌套try-with-resources,就像使用普通try-block一样:
try (First first = resource.get()) {
first.connect(...);
try (Second second = first.get()) {
// ...
}
}