从没有 return 结果的调用中获取结果?

Get result from call that doesn't return result?

我正在使用一个 API 调用结果,但 return 不调用结果本身。进行调用后,将调用一个单独的方法(侦听器),其中包含结果。这是我要实现的目标的示例:

public static void main (String[] args) {
    Object obj = someMethod();

    System.out.println("The object is" + obj + ", wooh!");
}

public void callObject() {
    // This is the call that sends a request for the object
}

public void receiveObject(Object object) {
    // This is the API method that is invoked with the result (cannot be changed)
}

// What I want to be able to do
public Object someMethod() {
    callObject();
    // return received object once received, but how?
}

callObject() 不是 return 对象,只是启动对象的检索。我想要一个调用该对象的方法,然后 return 在收到它时将其发送。我一直在研究 Callables 和 Future 结果,但我不确定如何实现它们。

有什么想法吗?谢谢!

这个怎么样。在您的 class 中引入一个新字段:

private Object result;

然后在 receiveObject(Object object) 方法中设置:

this.result = object;

在 someMethod() 中:

callObject();
while(this.result==null) {
    Thread.sleep(100);
}
Object answer = this.result;
this.result = null;
return answer;

应该可以正常工作,只要您为每个 API 请求创建此 class 的新实例。不要试图让这个 class 成为一个单例,它只会让事情变得不必要的复杂。

如果你真的需要一个单身人士,你可以将其概括为 private Object result; 到地图中,并想出一种方法来识别每个单独的 API 呼叫,比如一些呼叫者 ID。

最后,您还可以将 private Object result; 替换为 java.util.concurrent.CompletableFuture。然后在 receiveObject 方法中完成那个未来,并在 someMethod 中等待它(.get() 它)。这比使用线程睡眠循环更符合习惯。

怎么可能 return 没有东西可以 returned,int someMethod() return 词在哪里,callObject() return 没什么,因为它是 void。这样它将 return 一个对象

public Object someMethod() {
    return new Object();
}

最简单的情况:您以普通的阻塞方式发送请求,并希望能够在主线程执行时执行某些操作。为此,请使用 ExecutorService, usually created by a call to Executors,例如:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class ToyConc1 {
    public static void main(String[] args) throws InterruptedException,
            ExecutionException {
        ExecutorService exec = Executors.newCachedThreadPool();
        try {
            Callable<String> op1 = new Callable<String>() {
                @Override
                public String call() throws Exception {
                    return slowlyGetHttpPage("http://www.google.com");
                }
            }; 
            Callable<String> op2 = new Callable<String>() {
                @Override
                public String call() throws Exception {
                    return slowlyGetHttpPage("http://edition.cnn.com/");
                }
            }; 
            Future<String> resF1 = exec.submit(op1);
            Future<String> resF2 = exec.submit(op2);

            for (int i = 0; i < 20; i++) {
                System.out.println("doing useful work on the main thread...");
            }
            System.out.println("The object 1 is " + limit(resF1.get(), 1000) + ", wooh!");
            System.out.println("The object 2 is " + limit(resF2.get(), 1000) + ", wooh!");
        } finally {
            exec.shutdown();
            exec.awaitTermination(60, TimeUnit.SECONDS);
        }
    }

    private static String slowlyGetHttpPage(String urlName) throws InterruptedException,
            IOException {
        Thread.sleep(2000);
        URL url = new URL(urlName);
        URLConnection conn = url.openConnection();
        InputStream in = conn.getInputStream();
        InputStreamReader reader = new InputStreamReader(in); // wrong charset maybe
        BufferedReader br = new BufferedReader(reader);
        StringBuilder sb = new StringBuilder();
        try {
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            return sb.toString();
        } finally {
            br.close();
        }
    }

    private static String limit(String s, int length) {
        if (s == null) {
            return null;
        }
        if (s.length() <= length) {
            return s;
        }
        return s.substring(0, length) + " [and " + (s.length() - length) + " more]";
    }
}

或者,您用于发送请求和返回结果的 library/framework/technique 可能已经为您提供类似 Future or accept something like a callback (e.g. AsyncHttpClient 的东西。