java - 代表们——如何做?

标签 java android function interface callback

我正在尝试在我的 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/

相关文章:

java - PostGIS 函数不能在 java 中使用 hibernate ?

java - 测试 ArrayList .txt 文件是否有错误(不符合允许的格式)

android - Stripe.apiKey 未在 Android 中解析

javascript - 修改数组的每个单词

javascript - 函数给出 NAN 而不是字符串

javascript - 在 JS 中调用函数不支持参数

java - 是否可以在 Kotlin 中覆盖静态方法?

Android webview 下载数据/文本文件

android - 如何从 ViewFinder 自定义 zxing 条码扫描器的捕获屏幕边框

java - Java 中的工作线程