How to use callbacks in Java to call functions, just as I did in c#?
•
Java
I'm new to Java, but I need to write something like c# code (this is a hand-made prototype, just to illustrate what I need)
private void ParentFunc()
{
var worker = new WorkerClass()
worker.DoWork(e => console.Write("Progress" + e));
}
public class WorkerClass()
{
public method DoWork(Action<int> callback)
{
for (int i=1; i<1000; i++) callback.Invoke(i);
}
}
Little explanation I use asynctask in Android and call it outside the processor, but I want them to send back signals so that I can publish progress I don't want to put the interface on my asynctask
Solution
Since closures are not supported, you must use interfaces and anonymous inner classes
private void ParentFunc {
WorkerClass worker = new WorkerClass();
worker.doWork(new Callback<Integer>() {
public void invoke(Integer arg) {
System.out.println("Progress" + arg);
}
});
}
public class WorkerClass {
public doWork(Callback<Integer> callback) {
for (int i=1; i<1000; i++) callback.invoke(i);
}
}
public interface Callback<T> {
public void invoke(T arg);
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
