Java回调方法的最好示例

在C++中,实现回调非常容易,给被调模块传入一个函数指针,然后在被调模块中操作这个函数指针即可,实现很方便,效率也极高。当然了,Java也能实现,可是在网上看到了很多对Java回调方法的讲解,都不是非常简明易懂。今天我专门写个例子给大家分享,免得在实际使用中总是困惑。

示例思路:模拟一个拷贝大文件的过程,拷贝大型文件时需要消耗一定的时间,调用者不必阻塞等待,继续做自己的事情即可。等待拷贝文件的任务模块任务完成之后,会调用一个回调,通知调用者任务已经完成,当然了,在复制文件的中途,也可以通过此方法,实现复制文件的进度访问,非常容易。


需要先定义一个接口,CopyInterface.java文件内容:

package cn.example.file;

/**
 * @author liwei
 *
 */
public interface CopyInterface {
	public void start(String msg);
	public void updateProgress(long finished, long total);
	public void finish(String msg, Boolean status);
}
非常简单易懂,所以没有写的注释

下面是文件复制模块,CopyFile.java文件内容:

package cn.example.file;

/**
 * @author liwei
 * @since 1.5
 */
public class CopyFile extends Thread {
	
	private CopyInterface copyInterface = null;
	
	private long finished = 0;		// 已经完成的大小
	private long total = 0;			// 总大小
	
	public CopyFile(String srcFile, String desFile) {
		if (srcFile == null || desFile == null || srcFile.isEmpty() || desFile.isEmpty()) {
			System.err.println("Invalid parameters!");
			return ;
		}
		
		// 在这里模拟一个文件总大小的数值
		total = 100 * 1024 * 1024;	// 100MB
	}
		  
    public void setCallbackInterface(CopyInterface ci)  
    {
    	if (ci == null) {
    		System.err.println("Invalid CopyInterface!");
    	}
    	
    	this.copyInterface = ci;  
    }
	
	public void run() {
		if (copyInterface != null) {
			copyInterface.start("go!");
		}
		
		final long COPY_BLOCK_SIZE = 1024 * 1024;	// 假设每次拷贝1MB数据
		while (finished < total) {
			
			// 开始拷贝
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				// e.printStackTrace();
			}
			
			// 刷新拷贝进度
			finished = finished + COPY_BLOCK_SIZE;
			if (copyInterface != null) {
				copyInterface.updateProgress(finished, total);
			}
		}
		
		if (copyInterface != null) {
			copyInterface.finish("done!", true);
		}
	}
}
使用这个文件复制模块时,通过构造方法,定义它的源文件名和目标文件名,然后注册一个回调接口,对接口已经做了容易判断和处理,所以如果没注册,也不会崩溃。

拷贝文件的实现部分放在了线程中,所以调用者调用了start()方法之后不会阻塞,会立即返回,继续做自己的事情,在这里的run()方法中,任务开始之前通过copyInterface回调start()方法,通知调用者拷贝任务开始了,在任务进行中不断的调用updateProgress()方法刷新任务进度,拷贝完成之后再调用finished()方法,通知调用者任务完成了。

调用者的代码写在了CopyTest.java中,文件内容:

package cn.example.file;

/**
 * @author liwei
 *
 */
public class CopyTest implements CopyInterface {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		CopyFile copyFile = new CopyFile("a.txt", "b.txt");
		copyFile.setCallbackInterface(new CopyTest());
		copyFile.start();
		System.out.println("调用者线程不阻塞,继续做自己的事情...");
	}

	@Override
	public void start(String msg) {
		// TODO Auto-generated method stub
		System.out.println("Copying...started, message:" + msg);
	}

	@Override
	public void updateProgress(long finished, long total) {
		// TODO Auto-generated method stub
		String percent = String.format("%.2f", (double)finished / total * 100);
		System.out.println("Copying..." + percent + "%");
	}

	@Override
	public void finish(String msg, Boolean status) {
		// TODO Auto-generated method stub
		System.out.println("Copying...finished, message:" + msg);
		System.out.println("copy success:" + status);
	}
}

调用者必须实现回调接口中定义的方法,然后传入自己的实例,被调用者就可以通过这个接口实现回调,非常简单易懂,网上那些A调B,B又回调A,然后定义了一个接口C的示例,看的我晕,所以自己写了一个。

运行结果:

调用者线程不阻塞,继续做自己的事情...
Copying...started, message:go!
Copying...1.00%
Copying...2.00%
Copying...3.00%
Copying...4.00%
Copying...5.00%
Copying...6.00%
Copying...7.00%
Copying...8.00%
Copying...9.00%
Copying...10.00%
Copying...11.00%
Copying...12.00%
Copying...13.00%
Copying...14.00%
Copying...15.00%
Copying...16.00%
Copying...17.00%
Copying...18.00%
Copying...19.00%
Copying...20.00%
Copying...21.00%
Copying...22.00%
Copying...23.00%
Copying...24.00%
Copying...25.00%
Copying...26.00%
Copying...27.00%
Copying...28.00%
Copying...29.00%
Copying...30.00%
Copying...31.00%
Copying...32.00%
Copying...33.00%
Copying...34.00%
Copying...35.00%
Copying...36.00%
Copying...37.00%
Copying...38.00%
Copying...39.00%
Copying...40.00%
Copying...41.00%
Copying...42.00%
Copying...43.00%
Copying...44.00%
Copying...45.00%
Copying...46.00%
Copying...47.00%
Copying...48.00%
Copying...49.00%
Copying...50.00%
Copying...51.00%
Copying...52.00%
Copying...53.00%
Copying...54.00%
Copying...55.00%
Copying...56.00%
Copying...57.00%
Copying...58.00%
Copying...59.00%
Copying...60.00%
Copying...61.00%
Copying...62.00%
Copying...63.00%
Copying...64.00%
Copying...65.00%
Copying...66.00%
Copying...67.00%
Copying...68.00%
Copying...69.00%
Copying...70.00%
Copying...71.00%
Copying...72.00%
Copying...73.00%
Copying...74.00%
Copying...75.00%
Copying...76.00%
Copying...77.00%
Copying...78.00%
Copying...79.00%
Copying...80.00%
Copying...81.00%
Copying...82.00%
Copying...83.00%
Copying...84.00%
Copying...85.00%
Copying...86.00%
Copying...87.00%
Copying...88.00%
Copying...89.00%
Copying...90.00%
Copying...91.00%
Copying...92.00%
Copying...93.00%
Copying...94.00%
Copying...95.00%
Copying...96.00%
Copying...97.00%
Copying...98.00%
Copying...99.00%
Copying...100.00%
Copying...finished, message:done!
copy success:true


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
假设我们要在 C++ 中定义一个函数 `onEvent`,并且在 Java 中实现一个接口 `MyCallback`,我们可以通过以下步骤实现 C++ 方法通过 JNI 反射Java 方法: 1. 在 C++ 中定义函数 `onEvent`,并通过 JNI 将其注册到 Java 中: ```c++ class MyNativeClass { public: typedef void (*CallbackFunc)(int code); static void setCallback(JNIEnv* env, jobject obj, jobject callback) { jclass cls = env->GetObjectClass(callback); if (cls == NULL) return; jmethodID method = env->GetMethodID(cls, "onEvent", "(I)V"); if (method == NULL) return; callbackFunc_ = reinterpret_cast<CallbackFunc>(method); env->DeleteLocalRef(cls); callbackObj_ = env->NewGlobalRef(callback); } static void onEvent(int code) { if (callbackFunc_ != NULL && callbackObj_ != NULL) { JNIEnv* env = getJNIEnv(); env->CallVoidMethod(callbackObj_, reinterpret_cast<jmethodID>(callbackFunc_), code); } } private: static CallbackFunc callbackFunc_; static jobject callbackObj_; }; MyNativeClass::CallbackFunc MyNativeClass::callbackFunc_ = NULL; jobject MyNativeClass::callbackObj_ = NULL; extern "C" JNIEXPORT void JNICALL Java_com_example_MyClass_setCallback(JNIEnv* env, jobject obj, jobject callback) { MyNativeClass::setCallback(env, obj, callback); } ``` 2. 在 Java 中定义接口 `MyCallback`: ```java public interface MyCallback { void onEvent(int code); } ``` 3. 在 Java 中实现一个类 `MyClass`,并将 C++ 函数注册到该类中: ```java public class MyClass { static { System.loadLibrary("mylibrary"); } private static native void setCallback(MyCallback callback); public void doSomething() { // 用 C++ 中的 onEvent 函数,触发 MyNativeClass.onEvent(0); } } ``` 4. 在 Java 中实现 `MyCallback` 接口并注册到 `MyClass` 中: ```java public class MyCallbackImpl implements MyCallback { @Override public void onEvent(int code) { // 处理事件 } } MyClass myObject = new MyClass(); myObject.setCallback(new MyCallbackImpl()); ``` 这样,当 C++ 中用 `onEvent` 函数时,就会触发 Java 中实现的 `onEvent` 方法,从而实现了 C++ 方法通过 JNI 反射Java 方法
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

互联网速递520

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值