简体   繁体   中英

Open connection in try-with-resources - second resource depend on first

I would like to use try-with-resources. I have two resources, where second depend on first. After initialize first, I need to execute method on first resources. Next I can initialize second resource. What can I do it?

try (First first = resource.get());
     --Here I need run method: first.connect(...);
     Second second = first.get())
     {
      ...
     }

You can nest try-with-resources, just like you can with normal try-blocks:

try (First first = resource.get()) {
    first.connect(...);
    try (Second second = first.get()) {
        // ...
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM