Class AutoCloser<T,E extends Exception>

java.lang.Object
dev.metaschema.core.util.AutoCloser<T,E>
Type Parameters:
T - the resource type
E - the exception type that may be thrown if an error occurs when closing the resource
All Implemented Interfaces:
AutoCloseable

public final class AutoCloser<T,E extends Exception> extends Object implements AutoCloseable
Wraps a resource to make it AutoCloseable.
  • Method Details

    • autoClose

      @Owning @NonNull public static <T, E extends Exception> @Owning AutoCloser<T,E> autoClose(@NonNull T resource, @NonNull AutoCloser.Closer<T,E> lambda)
      Adapt the the provided resource to be AutoCloseable, using a provided closer lambda.

      The caller owns the returned wrapper and is responsible for closing it.

      Type Parameters:
      T - the resource's type
      E - the exception type that can be thrown when closing
      Parameters:
      resource - the object to adapt
      lambda - the lambda to use as a callback on close
      Returns:
      the resource wrapped in an AutoCloseable
    • getResource

      @NonNull public T getResource()
      Get the wrapped resource.
      Returns:
      the resource object
    • close

      public void close() throws E
      Specified by:
      close in interface AutoCloseable
      Throws:
      E extends Exception
    • preventClose

      @Owning @NonNull public static @Owning OutputStream preventClose(OutputStream out)
      Wraps the provided output stream to prevent the wrapped stream from being closed.

      This is useful for protecting standard streams. i.e. System.out, System.err.

      The caller owns the returned stream and is responsible for closing it.

      Parameters:
      out - the stream to wrap
      Returns:
      the new wrapped stream