Class AutoCloseableWrapper<T,​E extends Exception>

  • Type Parameters:
    T - The type of the object to wrap.
    E - The type of the exception that the close action may throw.
    All Implemented Interfaces:
    Serializable, AutoCloseable

    public final class AutoCloseableWrapper<T,​E extends Exception>
    extends Object
    implements AutoCloseable, Serializable
    Wrapper for an object that does not itself implement AutoCloseable, but needs to be closed in a different kind of fashion. This class wraps such objects and implements AutoCloseable to allow them to be used in try-with-resources statements.

    This class is serializable if the wrapped object and its close action is serializable.

    Since:
    8.3.0
    Author:
    XIMA MEDIA GmbH
    See Also:
    Serialized Form
    • Method Detail

      • wrapped

        public T wrapped()
        Gets the wrapped object.
        Returns:
        The wrapped object.
        Throws:
        IllegalStateException - If the wrapper has already been closed.
      • ofObject

        public static <T> AutoCloseableWrapper<T,​Exception> ofObject​(T wrapped)
        Creates a wrapper for the given object that will close the object when closed, if the object implements AutoCloseable; and do nothing otherwise.
        Type Parameters:
        T - The type of the object to wrap.
        Parameters:
        wrapped - The object to wrap.
        Returns:
        A new AutoCloseableWrapper that wraps the given object and closes it if necessary.
      • ofObjectQuiet

        public static <T> AutoCloseableWrapper<T,​RuntimeException> ofObjectQuiet​(T wrapped)
        Creates a wrapper for the given object that will close the object when closed, if the object implements AutoCloseable; and do nothing otherwise. If the close action throws an exception, it will be caught and ignored.
        Type Parameters:
        T - The type of the object to wrap.
        Parameters:
        wrapped - The object to wrap.
        Returns:
        A new AutoCloseableWrapper that wraps the given object and closes it if necessary.
      • withCloseAction

        public static <T,​E extends ExceptionAutoCloseableWrapper<T,​E> withCloseAction​(T wrapped,
                                                                                                    ITypedThrowingConsumer<? super T,​? extends E> close)
        Creates a wrapper for the given object that will call the given close action when closed.
        Type Parameters:
        T - The type of the object to wrap.
        E - The type of the exception that the close action may throw.
        Parameters:
        wrapped - The object to wrap.
        close - The action to perform when the object is closed.
        Returns:
        A new AutoCloseableWrapper that wraps the given object and invokes the given action when closed.