Java 8代码阅读

时间:2017-03-25 03:48:34

标签: java java-8

这段Java代码很难理解。这个DirExplorer是如何创建的? DirExplorer类链接是https://github.com/ftomassetti/analyze-java-code-examples/blob/master/src/main/java/me/tomassetti/support/DirExplorer.java 干杯, 代码如下:

 new DirExplorer((level, path, file) -> path.endsWith(".java"), (level, path, file) -> {
        System.out.println(path);
        System.out.println(Strings.repeat("=", path.length()));
        try {
            new VoidVisitorAdapter<Object>() {
                @Override
                public void visit(ClassOrInterfaceDeclaration n, Object arg) {
                    super.visit(n, arg);
                    System.out.println(" * " + n.getName());
                }
            }.visit(JavaParser.parse(file), null);
            System.out.println(); // empty line
        } catch (ParseException | IOException e) {
            new RuntimeException(e);
        }
    }).explore(projectDir);

2 个答案:

答案 0 :(得分:6)

让我们将代码重构为旧式以便于理解:

Filter filter = new Filter() {
    @Override
    public boolean interested(int level, String path, File file) {
        return path.endsWith(".java");
    }
};

FileHandler fileHandler = new FileHandler() {
    @Override
    public void handle(int level, String path, File file) {
        // Your long implementation for FileHandler
    }
};
new DirExplorer(filter, fileHandler).explore(projectDir);

变量filter是实现接口Filter的匿名类的实例,接口Filter只有一个方法,因此在Java 8中它是functional interface,并且上面的初始化代码可以通过lambda expression in Java 8缩短为:

Filter filter = (level, path, file) -> path.endsWith(".java");

FileHandler fileHandler = (level, path, file) -> {
    // Your implementation for FileHandler
};
new DirExplorer(filter, fileHandler).explore(projectDir);

此外,您可以内联两个变量,这导致代码为:

new DirExplorer((level, path, file) -> path.endsWith(".java"), (level1, path1, file1) -> {
        // Your implementation for FileHandler
    }).explore(projectDir);

答案 1 :(得分:1)

当它难以阅读时,我将其分解为更小,更易读的部分。 这更容易理解吗?

    Filter filter  = (level, path, file) -> path.endsWith(".java");
    FileHandler fileHandler = (level, path, file) -> {

        System.out.println(path);
        System.out.println(Strings.repeat("=", path.length()));
        try {
            new VoidVisitorAdapter<Object>() {
                @Override
                public void visit(ClassOrInterfaceDeclaration n, Object arg) {
                    super.visit(n, arg);
                    System.out.println(" * " + n.getName());
                }
            }.visit(JavaParser.parse(file), null);
            System.out.println(); // empty line
        } catch (ParseException | IOException e) {
            new RuntimeException(e);
        }
    };

    new DirExplorer(filter, fileHandler).explore(projectDir);