Callback mechanism of Java 8
callback, closures, java, java-8
Solution
Yes, you can replace the inner class definition. So long as the interface being expected by the method you are calling has 1 unimplemented method, you can use the lambda syntax.
So what you did above is correct. Also, as someone pointed out, there is the function reference syntax, but that function reference you pass has to have a signature that is coercable to your interface. For instance, take the Consumer interface:
public interface Consumer<T> {
void accept(T t);
}
public class MyClass {
void doSomething(Consumer<String> consumer) { }
}
In this case, you can pass any function reference to the "doSomething" method which has a void return, and accepts a single parameter as a string.
ie. myClassInstance.doSomething(System.out::println);
I'm not sure about eclipse, as i haven't used the latest versions, but I know Intellij 13 supports the lambda syntax. And even if you're not using java8, it will fold your code into that syntax to make it easier to read (don't worry, it doesn't save it that way, it's just a presentation thing that you can unfold if desired).
Problem
What is the best and easiest way to implement callback mechanism in java 8? Is it to easily replace inner class decleration with lambda experission? Like replacing ``` doSomethingAndRunThisCode(new Call() { @Override public void callback() { System.out.println("here I am called back"); } }); ``` with ``` doSomethingAndRunThisCode(() -> { System.out.println("here I am called back"); }); ``` But I think this is not all. Because pre java 8 way is even easier due to code complition of eclipse. Eclipse does nothing on java 8 way of implementing it (yet) .