Java 8 callback mechanism

What is the best and easiest way to implement a callback mechanism in java 8? Is it easy to replace internal class deviation with a lambda experiment? Like a replacement

    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 that is not all. Because pre java 8-way is even easier due to eclipse code matching. Eclipse does nothing on java 8 ways to implement it (for now).

+4
source share
1 answer

Yes, you can replace the definition of an inner class. As long as the interface expected by the method you call has 1 unimplemented method, you can use lambda syntax.

, , . , -, , , . , :

public interface Consumer<T> {
   void accept(T t);
}

public class MyClass { 
   void doSomething(Consumer<String> consumer) { }
}

"doSomething", void, .

.   myClassInstance.doSomething(System.out:: Println);

eclipse, , , Intellij 13 . java8, , ( , , , , ).

+5

Source: https://habr.com/ru/post/1537156/


All Articles