I've got some code which defines an anonymous inner class for a callback handler. This handler needs to assign a local variable, see below. I need to assign resp
in the callback and refer to it towards the end of the function. I am getting this error in Eclipse however:
The final local variable resp
cannot be assigned, since it is defined in an enclosing type
How can I fix this?
DoorResult unlockDoor(final LockableDoor door) {
final UnlockDoorResponse resp;
final boolean sent = sendRequest(new UnlockDoorRequest(door),
new ResponseAction() {
public void execute(Session session)
throws TimedOutException, RetryException, RecoverException {
session.watch(UNLOCK_DOOR);
resp = (UnlockDoorResponse)session.watch(UNLOCK_DOOR);
}
});
DoorResult result;
if (!sent) {
return DoorResult.COMMS_ERROR;
}
else {
return DoorResult.valueOf(resp.getResponseCode());
}
}
Here is a hack that would work in your case:
DoorResult unlockDoor(final LockableDoor door) {
final UnlockDoorResponse resp[] = { null };
final boolean sent = sendRequest(new UnlockDoorRequest(door), new ResponseAction() {
public void execute(Session session) throws TimedOutException, RetryException, RecoverException {
session.watch(UNLOCK_DOOR);
resp[0] = (UnlockDoorResponse)session.watch(UNLOCK_DOOR);
}
});
DoorResult result;
if (!sent) {
return DoorResult.COMMS_ERROR;
}
else {
return null == resp[0] ? null : DoorResult.valueOf(resp[0].getResponseCode());
}
}
If you want a cleaner solution, though, you have to define a named class for your handler, store the response in its field, and retrieve it using an accessor method.
Best regards, Stan.