quarta-feira, 3 de junho de 2009

String closures.

Since java has no closures, programming callbacks is a pain. Making a interface, using the interface in the function, implementing the interface and finally use the damn method. While java doesn't get interface injection, or whatever it is called when the callee defines the interface and callers automagically verify the type, there is always reflection.

I did a few utility classes to call methods reflectively for the main closure types in java: Action, Listener, Runnable and Swingworker. Of these the interesting case is SwingWorker that has two important methods. Worked around by saving the result of the first and passing it to the second.

Then i do code like this:
DynamicSwingWorker.createWithFinished(this,"swingWorkerReadFinished","swingWorkerRead",uri).start();

/**
* Returns if it had success or not
*/
public Boolean swingWorkerRead(URL uri) {
try {
Integer index = getBookMarks().getIndex(uri);
pane.read(uri, index);
return true;
} catch (IOException ex) {
getBookMarks().remove(uri);
return false;
} catch (Exception e){
return false;
}
}

/**
* Receives if had success
*/
public void swingWorkerReadFinished(Boolean success) {
unBlockView(success);
}

Easy.

Sem comentários:

Enviar um comentário