简体   繁体   English

如果实现了AutoCloseable,则帮助调用close()的助手吗?

[英]Helper to call close() if implements AutoCloseable?

Is there any helper method in the JDK or common libraries that does this: JDK或公共库中是否有任何帮助程序可以做到这一点:

if (resource instanceof AutoCloseable) {
    ((AutoCloseable) resource).close();
}

Just a one-liner to call an object's close() if applicable. 如果适用的话,只需调用一个直线即可调用对象的close()

I know about try-with-resources, that's not applicable to this situation. 我知道try-with-resources,不适用于这种情况。 And I know that not all classes that have a close() method implement AutoCloseable . 而且我知道并非所有具有close()方法的类都实现AutoCloseable But, I seem to write the above over and over.. 但是,我似乎一遍又一遍地写了上面。

Here is apache commons closeQuietly adapted for AutoCloseable: 这是Apache Commons closeQuietly适用于AutoCloseable:

  static void closeQuietly(AutoCloseable closeable) {
    try {
      if (closeable != null) {
        closeable.close();
      }
    }
    catch (Exception swallowed) {
    }
  }

since google sent me here for that case :) 由于谷歌发送给我在这种情况下:)

Edit : 编辑

Check this: 检查一下:

class CloserHelper
{
    public static void close(Object object)
    {
        if (object instanceof AutoCloseable)
        {
            try
            {
                ((AutoCloseable) object).close();
            }
            catch (Exception ignored) { }
        }
    }
}

I can think to something like this 我可以这样想

class CloserHelper
{
    public static void close(AutoCloseable obj) throws Exception
    {
        obj.close();
    }
}

Then 然后

CloserHelper.close(resource);

If the object is not a AutoCloseable you cannot just call it 如果对象不是自动AutoCloseable对象,则不能直接调用它


If you want to ignore exceptions 如果要忽略异常

class CloserHelper
{
    public static void close(AutoCloseable obj)
    {
        try
        {
            obj.close();
        }
        catch (Exception e) { }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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