I’ve needed to get a value back from an anonymous inner class. Inner classes can only close over final variables, of course, which leads to this horrible workaround:
public String sampleMethod(){
final String[] output = new String[1];
findResult(new SampleOperation(){
@Override
private void perform(){
output[0] = "result";
}
});
return output[0];
}
private void findResult(SampleOperation op){
op.perform();
}
private static interface SampleOperation {
void perform();
}
Obviously a simplified example; here the class is easily removable, but the principal of the problem is there. If there is a dependency further down (inside findResult(), such as a latch that needs triggered) then unwrapping such a class becomes impractical.
Wrapping the final array means it’s accessible, but this has one of the worst smells I’ve ever come across.
Is there a sane way to get a return type from such a delegate? (i.e. Not use this?)
The problem here is that
SampleOperation.performreturns void. Just make it returnString(or be generic) and it’s fine:Ultimately, whenever you’re thinking about “I need to get a value back” you should be thinking about a value being returned from a method.