我正在尝试在我的 android java 项目中使用接口(interface)。回调接口(interface)似乎是 C# 委托(delegate)的答案,但我无法理解它,我读过其他类似的问题,但同样,我无法让它满足我的需求或让它工作。我需要的是调用A类中的一个函数,该函数作为参数传递给B类。当B类完成任务时,通过调用先前保存在变量中的函数将结果返回给A:
class A {
B myBClass;
public A() {
myBClass = new B();
myBClass.doSomething(ResultFunction);
//Continue doing other tasks
}
public void ResultFunction(<result parameters>) {
//do something with the result from the task in myBClass
}
}
class B {
Function myCallback;
public B() {
}
public void doSomething(ResultFunction) {
myCallback = callback;
//does something
SomethingFinished();
}
private void SomethingFinished() {
myCallback.call(<result of doSomething>);
}
}
最佳答案
有两种方法可以做到这一点:
1)使用匿名类:
从类 B
中的 doSomething
方法中删除 ResultFunction
参数
并在类A
中重新实现它
public A() {
myBClass = new B() {
@Override
public void doSomething() {
super.doSomething();
//do here what you need what you want to do in B class
}
}
myBClass.doSomething();
//Continue doing other tasks
}
2) 使用Callable
接口(interface)
interface Callable {
public void call();
}
传递它而不是ResultFunction
class A {
B myBClass;
Callable callable = new Callable {
@Override
public void call() {
//do here what you need what you want to do in B class
}
}
public A() {
myBClass = new B();
myBClass.doSomething(callable);
//Continue doing other tasks
}
}
class B {
Callable myCallback;
public B() {
}
public void doSomething(Callable callable) {
myCallback = callable;
//does something
SomethingFinished();
}
private void SomethingFinished() {
myCallback.call();
}
}
使用 lambda 看起来会更好一点
public A() {
myBClass = new B();
myBClass.doSomething(()->{
//do here what you need what you want to do in B class
});
//Continue doing other tasks
}
关于java - 代表们——如何做?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48009623/