- This is not an interface, but an anonymous class that implements the interface. These are different things)
- You really don't get to write to a local variable, which is what the compiler wrote. The reason is very simple - methods of an anonymous class can be called at any time, that is, asynchronously, and this can happen much later, outside of this function. Actually no variable and will not be at that moment. In principle, this can be bypassed - AtomicReference and .set ().
Judging by what I see here, you have AsyncHttpClient - judging by the name, the method code will really be called asynchronously (that is, it is not known when). That is, the Detect function will be executed instantly, but the response will come to you much later, will be received in general in a separate, different stream and when this happens, the onSuccess interface method will be onSuccess . So return resp; - does not make any sense. And even using AtomicReference will result in null if you try to read the value immediately outside the function. This problem is solved in two ways:
Synchronization. Just wait for the request to complete, for example, something like this:
AtomicReference<String> result = Detect("..."); while(result.get() == null) {}
Suit in principle, if you do it in a separate thread. But such code is terrible, it is better to look for a synchronous client that does it all for you.
In this case, your interface is a callback, which will be called when the data is received. And therefore it is advisable to go to asynchronous programming. In this case, you are moving from sequential code:
Object result = firstAction(); secondAction(result);
To asynchronous:
firstAction(new Resulthandler() { void actionFinished(Object result) { secondAction(result); } });