csdn上看到一帖子讲java回调机制,有代码如下:
- Java code
public interface ICallback { public void func();} public class ClassWithCallbackFunction implements ICallback{ public ClassWithCallbackFunction() { } public void func(){ System.out.println("cccccccccccccccccc"); }} public class Caller { ICallback callback; public void doCallback() { callback.func(); } public void setCallback(ICallback callback) { this.callback = callback; }} public class MainClass { public MainClass() { } public static void main(String[] args) { Caller caller = new Caller(); caller.setCallback(new ClassWithCallbackFunction() { public void func() { System.out.println("aaaaaaaaaa"); } }); caller.doCallback(); //????????????? why not print }}
为什么MainClass的caller.doCallback()没有打印语句,感觉要嘛打印aaaaaaaa,要嘛打印cccccc,但不打印,why?
------解决方案--------------------
- Java code
//我的机器能打印aaaaaaaaaa,你的机器神马牌子的,高级不愿意打印它们interface ICallback { public void func();}class ClassWithCallbackFunction implements ICallback { public ClassWithCallbackFunction() { } public void func() { System.out.println("cccccccccccccccccc");//实现接口方法 }}class Caller { ICallback callback; public void doCallback() { callback.func(); } public void setCallback(ICallback callback) { this.callback = callback; }}public class MainClass { public MainClass() { } public static void main(String[] args) { Caller caller = new Caller(); caller.setCallback(new ClassWithCallbackFunction() { public void func() {//这里已经重写了func方法,你不重写这个它,它就会打印"cccccccccccccccccc" System.out.println("aaaaaaaaaa"); } }); caller.doCallback(); // ????????????? why not print }}/*output:aaaaaaaaaa*/
------解决方案--------------------
eclipse 中 调用 debug 来调试
既可知道整个代码的执行步骤 即程序的调用过程
也能知道程序运行结果的由来
------解决方案--------------------
这里的回调也就是函数的手动调用吧.
------解决方案--------------------
lz,你再试试,确实打印了,是aaaaaaaa!