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).
We can also call Lambda expressions as the instance of functional interface. Before Java 8, we had to create anonymous inner class objects or implement these interfaces.
In Java 8, there are 4 main functional interfaces are introduced which could be used in different scenarios.
Java 8 provides some built-in functional interfaces and if we want to define any functional interface then we can make use of the @FunctionalInterface annotation. It will allow us to declare only a single method in the interface.
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)
}
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