Sobes.tech
Junior — Middle

What methods can be used to invoke a callback function in a Java Bean?

sobes.tech AI

Answer from AI

In Java Bean, calling a callback function can be implemented in several ways:

  1. Using an interface with a callback method. An interface with a callback method is created, which is implemented by another class. A reference to an object implementing the interface is passed to the Bean, and the method is called.

  2. Using lambda expressions or functional interfaces (starting from Java 8). A functional interface (e.g., Consumer, Runnable) can be passed and its method invoked.

  3. Through events and listeners. The Bean can support registration of listeners and call their methods when an event occurs.

Example with an interface:

public interface Callback {
    void call();
}

public class MyBean {
    private Callback callback;

    public void setCallback(Callback callback) {
        this.callback = callback;
    }

    public void doWork() {
        // some logic
        if (callback != null) {
            callback.call();
        }
    }
}

// Usage:
MyBean bean = new MyBean();
bean.setCallback(() -> System.out.println("Callback called!"));
bean.doWork();