Is there a pre-Java-8 functional interface that's a drop in replacement for java.util.function.Consumer<T>?

StackOverflow https://stackoverflow.com/questions/22157957

  •  19-10-2022
  •  | 
  •  

Question

In anticipation of moving to Java 8, I'm trying to write my code in a way that's conducive to using lambdas.

I have a need for a functional interface with a single method that takes one argument of some type T and returns void. This is the signature of java.util.function.Consumer's accept() method, but of course I can't use that yet.

Is there another interface in the standard Java 7 (and preferably Java 6) API that I can use instead? I know I can create my own, but esp. until this code is ported to Java 8, it's better for readability if I can use a standard interface that's already familiar from the standard Java 6/7 APIs.

The closest thing I've found so far is com.google.common.base.Function<T,Void>, but (a) it's not part of the standard Java API and (b) its documentation says "instances of Function are generally expected to be referentially transparent -- no side effects", which is contrary to my intended use (with a Void return type).

Was it helpful?

Solution

You can create your own interface:

public interface Invokable <T>{
    public void invoke(T param);
}

Alternatively, as suggested, you could use the same interface as the Java 8 Consumer. The source is included in the Java 8 JDK Early Access download, here with all the comments and annotations removed:

public interface Consumer<T>{
    void accept(T t)
    default Consumer<T> andThen(Consumer<? super T> after)
}

OTHER TIPS

Ha, found one! Look in the JavaEE 7 API: The interface javax.websocket.MessageHandler.Whole should be what you are looking for.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top