Issue
I'm studyin' some Java code written by my ex-colleague, and I've found something I cannot understand properly. Here we have a method, getGeneAvailableTaxonomies(), that seems to contain a method call with its own declaration, accept(). Is it true? Is it possibile?
Here's the code part: I cannot understand the meaning of the program from FilenameFilter() to the end.
public List<Integer> getGeneAvailableTaxonomies() {
List<Integer> availableTaxon = new ArrayList<Integer>();
File dataDirectory = new File(_currentApplicationPath, String.format("Data"));
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith("gene_") && name.endsWith("_info.info"); //get all info files...
}
};
String[] children = dataDirectory.list(filter);
for(String child:children) {
availableTaxon.add(Integer.parseInt(child.substring(child.indexOf("_")+1, child.lastIndexOf("_"))));
}
return availableTaxon;
}
Solution
The part of the code where you see the accept()
method being defined is what's called an anonymous class.
FilenameFilter filter = new FilenameFilter() { public boolean accept(File dir, String name) { return name.startsWith("gene_") && name.endsWith("_info.info"); //get all info files... } };
What's going on here is the creation of a new Class that is-a FilenameFilter. They're implementing/overriding the accept method. Think of it like this, but in one statement:
class MyFilenameFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
return name.startsWith("gene_") && name.endsWith("_info.info");
}
}
FilenameFilter filter = new MyFilenameFilter()
Answered By - csturtz
Answer Checked By - Marie Seifert (JavaFixing Admin)