I personally feel that Java is desperate for some support for closing. In the meantime, I implemented a general method callback in Java. It is posted on my website .
The advantage of this approach is its versatility. The goal was to write an API like a file system tree, without having to define an interface each time, instead assigning a method in the code using the API to do the job.
For example, moving the file system tree to process each file:
Process Directory Tree API
static public int processDirectory(File dir, Callback cbk, FileSelector sel) { return _processDirectory(dir,new Callback.WithParms(cbk,2),sel); } static private int _processDirectory(File dir, Callback.WithParms cbk, FileSelector sel) { int cnt=0; if(!dir.isDirectory()) { if(sel==null || sel.accept(dir)) { cbk.invoke(dir.getParent(),dir); cnt++; } } else { cbk.invoke(dir,(Object[])null); File[] lst=(sel==null ? dir.listFiles() : dir.listFiles(sel)); if(lst!=null) { for(int xa=0; xa<lst.length; xa++) { File ent=lst[xa]; if(!ent.isDirectory()) { cbk.invoke(dir,ent); lst[xa]=null; cnt++; } } for(int xa=0; xa<lst.length; xa++) { File ent=lst[xa]; if(ent!=null) { cnt+=_processDirectory(ent,cbk,sel); } } } } return cnt; }
Using the process catalog API
Using the method described above, I can now very easily process the directory tree for any operation; scanning, counting, listing, etc. With minor changes to call a callback in the directory, both before and after downstream operations, it was also possible to delete the file / tree (an additional parameter is required to indicate the background of the call message).
static private final Method COUNT =Callback.getMethod(Xxx.class,"callback_count",true,File.class,File.class); ... IoUtil.processDirectory(root,new Callback(this,COUNT),selector); ... private void callback_count(File dir, File fil) { if(fil!=null) { // file is null for processing a directory fileTotal++; if(fil.length()>fileSizeLimit) { throw new Abort("Failed","File size exceeds maximum of "+TextUtil.formatNumber(fileSizeLimit)+" bytes: "+fil); } } progress("Counting",dir,fileTotal); }