繁体   English   中英

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

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

JDK或公共库中是否有任何帮助程序可以做到这一点:

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

如果适用的话,只需调用一个直线即可调用对象的close()

我知道try-with-resources,不适用于这种情况。 而且我知道并非所有具有close()方法的类都实现AutoCloseable 但是,我似乎一遍又一遍地写了上面。

这是Apache Commons closeQuietly适用于AutoCloseable:

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

由于谷歌发送给我在这种情况下:)

编辑

检查一下:

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

我可以这样想

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

然后

CloserHelper.close(resource);

如果对象不是自动AutoCloseable对象,则不能直接调用它


如果要忽略异常

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