关于java的回调方法
前言
As we know JS支持"方法作为函数参数",所以回调方法很容易实现,可是java并不支持。但在java式android编程中我们可以看到很多异步的回调。那么android是如何实现的呢?在此我们并不讨论类似RXJs、RXJava的新技术,只是用纯原生的java思想实现回调
知识点
接口、多态、异步、多线程、内部类
正文
直接上代码
package com.util.Super;
public class CallBackFnc {
/**
* 定义内部接口用于回调
* @author wz
*
*/
interface Listener {
void OnListen();
//无参回调
void OnListen(String s);
//带参回调
}class A implements Listener {
static final String METHOD_ONE="方式一";
static final String METHOD_TWO="方式二";
static final String METHOD_THREE="方式三";
String type="默认方式";
public A(String type) {
this.type=type;
}
/**
* 问问题
*/
public void Question() {System.out.println("[A]:向B问问题");
//方式一
new Thread(new Runnable() {
public void run() {
System.out.println(METHOD_ONE);
//System.out.println("");
B b = new B();
b.answer(METHOD_ONE,5000,new Listener() {// 匿名内部类 android很多基于此
public void OnListen(String s) {
System.out.println("[A]:"+METHOD_ONE+"获取了答案:"+s);
System.out.println();
}
public void OnListen() {
}
});
}
}).start();
//方式二
new Thread(new Runnable() {
public void run() {
System.out.println(METHOD_TWO);
B b = new B();
b.answer(METHOD_TWO, 3000, new A(METHOD_TWO));
}
}).start();
//方式三
System.out.println(METHOD_THREE);
B b=new B();
b.answer(METHOD_THREE, 1000, this);
System.out.println("Question 执行完毕");
}@Override
public void OnListen(String s) {
System.out.println("[A]:"+this.type+"知道答案了: " + s);
System.out.println();
}
@Override
public void OnListen() {}}class B {
/**
* 回答问题(耗时操作)
*/
public void answer(String name,int time,Listener listener) {
new Thread(new Runnable() {
public void run() {
try {
//Thread.sleep(time);
System.out.println("[B]:"+name+"向我问问题,B思考了"+time+"毫秒");
listener.OnListen(name+",我是B的子线程");
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
//测试
public static void main(String[] args) {
CallBackFnc cbf = new CallBackFnc();
CallBackFnc.A a = cbf.new A("A from main");
a.Question();
System.out.println("main线程执行完毕");
}
}
看一眼结果
文章图片
测试结果 总结 【关于java的回调方法】多思考,多问问题,多动手
推荐阅读
- 热闹中的孤独
- JAVA(抽象类与接口的区别&重载与重写&内存泄漏)
- 放屁有这三个特征的,请注意啦!这说明你的身体毒素太多
- 一个人的旅行,三亚
- 布丽吉特,人生绝对的赢家
- 慢慢的美丽
- 尽力
- 一个小故事,我的思考。
- 家乡的那条小河
- 《真与假的困惑》???|《真与假的困惑》??? ——致良知是一种伟大的力量