I have repeatedly find myself wanting to use an interface that looks like this:
interface Handler<T> {
  void handle(T toHandle);
}
It's particularly useful in situations where you want to enforce a try-finally structure around a resource, without relying on the API user to do this.
Your API implementation can then look like:
 public void loadResource(Handler<SomeResource> resourceHandler) {
    SomeResource r = fetchTheResource();
    try {
      resourceHandler(r);
    finally {
      r.close();
    }
 }
...and the API consumer can safely do:
loader.loadResource(new Handler<SomeResource>() {
  public void handle(SomeResource resource) {
    // use the resource, no need to worry about closing it.
  }
});
I'm aware of the Closeable interface. That's not quite so general purpose - it can't force the consumer to close the resource correctly.
The interface might equally be called Receiver. Guava has Supplier which is pretty much the opposite, but no Receiver.
Is there some core interface that has this structure that I have missed? Am I somehow doing something that everyone else considers overkill?
I note the exact same question has been asked in a C# context: Does this interface already exist in the standard .NET libraries?
All Known Implementing Classes: href_handler public abstract interface handler. This is the interface that represents objects which get called when events happen at certain points in the structure. Method Summary.
A Handler object takes log messages from a Logger and exports them. It might for example, write them to a console or write them to a file, or send them to a network logging service, or forward them to an OS log, or whatever. A Handler can be disabled by doing a setLevel(Level.
Java 8 has the interface java.util.function.Consumer<T>.
If you can't make use of Java 8, but you have Guava, it's kind of like a com.google.common.base.Function<T, Void>. Yes, I know this looks a bit smelly, but it does resemble what you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With