[Java] anonymous inner class issue
It seems that if an anonymous inner class implements an interface ,then its constructor can't have argument。If really need arguments, theorectically two solutions:
However, if the class has the possibility to be used somewhere else, better give it a name。
- define a method which takes arguments (must be "final"). The method does nothing but return an anonymous class, which uses the method's arguments。
- see the exmaple below:
public Destination dest(final String dest) {
return new Destination() {
private String label = dest;
public String readLabel() { return label; }
};
}
import java.io.*;
import java.util.*;
abstract class NewFilenameFilter implements FilenameFilter{
protected String start, end;
NewFilenameFilter(String s, String e){
start = s;
end = e;
}
}
public class NameFilter{
public static void main(String argv[]){
if(argv.length != 1){
System.out.println("must have one argument!");
System.exit(1);
}
File f = new File(argv[0]);
if( !f.exists()){
System.out.println(argv[0] + " does not exists");
System.exit(1);
}
String s[] = f.list(new NewFilenameFilter("u", "c"){
public boolean accept(File dir, String filename){
boolean isMatch = true;
isMatch &= filename.startsWith(start);
isMatch &= filename.endsWith("." + end);
return isMatch;
}
});
/* print s */
}
}
However, if the class has the possibility to be used somewhere else, better give it a name。
Comments