//: DirList2.java
// Uses Java 1.1 anonymous inner classes
import java.io.*;
public class DirList2 {
    public static FilenameFilter
    filter(final String afn) {
// Creation of anonymous inner class:
        return new FilenameFilter() {
            String fn = afn;
            public boolean accept(File dir, String n) {
// Strip path information:
                String f = new File(n).getName();
                return f.indexOf(fn) != -1;
//                return true;
            }
        }; // End of anonymous inner class
    }
    public static void main(String[] args) {
        try {
            File path = new File(".");
            String[] list;
            if(args.length == 0)
                list = path.list();
            else
                list = path.list(filter(args[0]));
            for(int i = 0; i < list.length; i++)
                System.out.println(list[i]);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
} ///:~

注意 filter()的自变量必须是 final。这一点是匿名内部类要求的,使其能使用来自本身作用域以外的一个对象。

                                                                                                                                                      P.290

注意上面这一句话!

但是我在IntelliJ IDEA 2023.1.4 (Ultimate Edition),Java版本 "18.0.2" 2022-07-19环境下,不加final也可以正常运行。