在Java中,回調機制可以通過以下幾種方式來實現:
public interface Callback {
void onCallback();
}
public class CallbackExample {
private Callback callback;
public void setCallback(Callback callback) {
this.callback = callback;
}
public void doSomething() {
// 執行某些操作
// 觸發回調
if (callback != null) {
callback.onCallback();
}
}
}
public class Main {
public static void main(String[] args) {
CallbackExample example = new CallbackExample();
example.setCallback(() -> System.out.println("Callback called"));
example.doSomething();
}
}
public class CallbackExample {
public void setCallback(Callback callback) {
// ...
}
public void doSomething() {
// ...
}
}
public class Main {
public static void main(String[] args) {
CallbackExample example = new CallbackExample();
example.setCallback(new Callback() {
@Override
public void onCallback() {
System.out.println("Callback called");
}
});
example.doSomething();
}
}
public class CallbackExample {
public void setCallback(Callback callback) {
// ...
}
public void doSomething() {
// ...
}
}
public class Main {
public static void main(String[] args) {
CallbackExample example = new CallbackExample();
example.setCallback(() -> System.out.println("Callback called"));
example.doSomething();
}
}
無論使用哪種方式,回調機制都可以實現在一個對象中發生某些事件時通知另一個對象,并調用其特定方法進行處理。