C语言中回调函数由指针实现,java 中没有指针,可以通过以下方法实现:

1
2
3
public interface MyCallInterface{
public void method();
}
1
2
3
4
5
6
public Client implements MyCallInterface{
@Override
public void method(){
//TODO: 回调内容
}
}

调用时:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Caller{
private MyCallInterface callInterface;

public Caller(){
}

public void setCallFunc(MyCallInterface callInterface){
this.callInterface = callInterface;
}

public void call(){
callInterface.method();
}
}

1
2
3
4
5
6
7
public class Test{
public static void main(String args){
Caller caller = new Caller();
caller.setCallFunc(new Client());
caller.call();
}
}

或者
1
2
3
4
5
public class Caller{
public void call(Client client){
client.method();
}
}

1
2
3
4
5
6
public class Test{
public static void main(String args){
Caller caller = new Caller();
caller.call(new Client());
}
}

文章目录