在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();
}
}
无论使用哪种方式,回调机制都可以实现在一个对象中发生某些事件时通知另一个对象,并调用其特定方法进行处理。