如何使我的方法 return 成为回调?

How can i make my method return a callback?

我正在尝试使用 java binance api 为交易机器人编写代码。 我想做的是使用异步库中的客户端来创建一个方法来获取 data/candlesticks 然后 return 它。

我的问题是异步客户端 return 对回调的响应,我现在知道如何处理它,使我的方法 return 数据如下例所示:

    public List<Candlestick> asyncGetCandles(){
    //get the data
        return response /**List<Candlestick>response*/
    }

这是我目前得到的:

    public void asyncGetCandles() throws ParseException, IOException {

    BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance();
    BinanceApiAsyncRestClient asyncClient = factory.newAsyncRestClient();

    long start = dateTime.startOfListing();
    long now = System.currentTimeMillis();

    BinanceApiCallback<List<Candlestick>> callback = response -> {
        System.out.println(response);//prints 1000 candles
    };


    asyncClient.getCandlestickBars("BTCUSDT", CandlestickInterval.HOURLY, 1000, start, now, callback);

    /**How to return the response here?*/
}

如能提供有关如何执行此操作的任何帮助,我们将不胜感激!

它应该看起来像这样:

package Whosebug;

import java.io.IOException;
import java.text.ParseException;
import java.util.List;

public class ReturnAsyncCallback {
    interface BinanceApiCallback<T> { // either this usecase with interface
        BinanceApiCallback<T> run(String response);
    }
    abstract class BinanceApiCallback2<T> { // or this usecase with abstract base class
        abstract BinanceApiCallback<T> run(String response);
    }
    static class Candlestick {

    }

    public BinanceApiCallback<List<Candlestick>> asyncGetCandles() throws ParseException, IOException {

        final BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance();
        final BinanceApiAsyncRestClient asyncClient = factory.newAsyncRestClient();

        final long start = dateTime.startOfListing();
        final long now = System.currentTimeMillis();

        final BinanceApiCallback<List<Candlestick>> callback = (response) -> {
            System.out.println(response);//prints 1000 candles
        };


        asyncClient.getCandlestickBars("BTCUSDT", CandlestickInterval.HOURLY, 1000, start, now, callback);

        /**How to return the response here?*/
        return callback;
    }

}

请注意,lambda 表达式有两种方式。两者都需要一个 class 和一个抽象(未实现)方法:

  1. 使用只有 1 个(抽象)方法的接口,可以有任意多的默认方法。
  2. 使用一个抽象基 class 和一个抽象方法。

我的示例的附加说明:

  1. 内部 classes BinanceApiCallback 和 BinanceApiCallback2 以及 Candlestick 仅在 http://sscce.org/

进一步问题的提示:

  1. 您的代码不是 http://sscce.org/,因此我们很难回答。