java的回调函数
首先需要一个接口interface,两个类A和B。
在类A中,要有一个接口的属性,有一个有参构造,参数是接口。最后有一个方法methead(),methead()方法中用传入接口点的方式调用需要回调的方法。
在类B中,第一步是实现接口 。然后需要建一个类A的对象,建对象的同时需要把实现的接口传入进去。并且有一个需要被回调的方法。
这是类A
- public class A
- {
- public intef it;
- public void A(interf it)
- {
- this.it= it;
- }
- public void call(){
- this.it.method();
- }
- }
这是接口
- public interface intef
- {
- public void method();
- }
这是类B
- public class B implements intef
- {
- public void method()
- {
- System.out.println("我是被回调的方法");
- }
- public static void main(String args[])
- {
- A a = new A(new B());
- a.call();
- }
- }
回调函数可以用来测试性能,也就是该方法运行所用的时间。