- java.lang.Object
-
- eu.ess.xaos.core.util.AutoCloser<T>
-
- Type Parameters:
T
- The type of the object wrapped by this class.
public class AutoCloser<T> extends Object
This utility class allows to use non-AutoCloseable
classes in auto-closeable contexts.For example, imagine to have the following class:
public class NotAutoclosable { public NotAutoclosable() { ... } public void dispose() { ...to be called to free resources... } ... }
This class can be used in the following way:
NotAutoclosable nac = new NotAutoclosable(); try { ...use nac.xxx methods... } finally { nac.dispose(); }
AutoCloser
simplify things without requiring to modifyNotAutoclosable
to implementAutoCloseable
:try { var nacs = AutoCloser.of(new NotAutoclosable()).by(sp -> sp.get().dispose()) ) { ...use nacs.get().xxx methods... }
- Author:
- Peter Verhas, claudio.rosati@esss.se
- See Also:
- Box old objects to be autoclosable
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description class
AutoCloser.AutoClosableSupplier
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description AutoCloser.AutoClosableSupplier
by(Consumer<Supplier<T>> closer)
Provides this wrapping class the mean to "close" the wrapped resource in an auto-closable context.static <T> AutoCloser<T>
of(T resource)
Returns an instance of this class, wrapping the givenresource
, to be used in an auto-closable context.
-
-
-
Method Detail
-
of
public static <T> AutoCloser<T> of(T resource)
Returns an instance of this class, wrapping the givenresource
, to be used in an auto-closable context.- Type Parameters:
T
- The type of the wrappedresource
.- Parameters:
resource
- The non-AutoCloseable
resource to be wrapped.- Returns:
- An instance of this class to be used an auto-closable context.
-
by
public AutoCloser.AutoClosableSupplier by(Consumer<Supplier<T>> closer)
Provides this wrapping class the mean to "close" the wrapped resource in an auto-closable context.- Parameters:
closer
- A consumer whoseConsumer.accept(Object)
method will be called in an auto-closable context to close the wrapped resource. The parameter of theaccept
method will be an instance ofAutoCloser.AutoClosableSupplier
, a supplier whoseSupplier.get()
method will return the wrapped resource.- Returns:
- An
AutoCloser.AutoClosableSupplier
instance that will be passed as parameter to thecloser
'saccept
method when the wrapped resource needs to be closed in an auto-closable context.
-
-