java中回调函数的用法
C语言中回调函数由指针实现,java 中没有指针,可以通过以下方法实现:
1 | public interface MyCallInterface{ |
1 | public Client implements MyCallInterface{ |
调用时:1
2
3
4
5
6
7
8
9
10
11
12
13
14public 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
7public class Test{
public static void main(String args){
Caller caller = new Caller();
caller.setCallFunc(new Client());
caller.call();
}
}
或者1
2
3
4
5public class Caller{
public void call(Client client){
client.method();
}
}1
2
3
4
5
6public class Test{
public static void main(String args){
Caller caller = new Caller();
caller.call(new Client());
}
}