Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a standard Java Receiver/Handler interface?

Tags:

java

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?

like image 550
Tim Gage Avatar asked Jul 08 '14 13:07

Tim Gage


People also ask

What is a handler interface?

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.

What is a Java handler?

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.


1 Answers

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.

like image 148
Ray Avatar answered Sep 21 '22 01:09

Ray