匿名类Java问题 [英] Anonymous class java question

查看:48
本文介绍了匿名类Java问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试了解有关匿名类的参数。我看过的书中的示例没有论据,或者没有很好地解释它们。这是代码(来自Java in Nutshell 2nd Edition示例5-8,是的,我知道它很旧了:-)...

I'm trying to understand arguments with respect to anonymous classes. The examples in books I've seen either don't have arguments or else don't explain them well. Here's the code (from Java in a Nutshell 2nd edition example 5-8 and yes I know it's old :-)...

import java.io.*;  

//Print out all the *.java files in the directory.
public static void main(String[] args)  
{  
  File f = new File(args[0]);  
  String[] list = f.list(new FilenameFilter() {
    public boolean accept(File f, String s) {  
      return s.endsWith(".java");  
    }  
  });  
  for (int i = 0; i < list.length; i++)  
    System.out.println(list[i]);  
  }
}  

我的问题是文件名f如何应用于'accept'的'File f'参数,以及'String s'的参数从何而来?为什么会从FilenameFilter构造函数中调用 accept方法?

谢谢!

My questions is how the filename f gets applied to the 'File f' argument of 'accept', and also where does the 'String s' argument come from? Why does the 'accept' method get called, is it from the FilenameFilter constructor perhaps?
Thanks!

推荐答案

如果您查看Java api的源文件,您将在File.java中找到以下内容:

if you take a look into the source files of the java api, you will find following in File.java:

public String[] list(FilenameFilter filter) {
            String names[] = list();
            if ((names == null) || (filter == null)) {
                return names;
            }
            List<String> v = new ArrayList<>();
            for (int i = 0 ; i < names.length ; i++) {
                if (filter.accept(this, names[i])) {
                    v.add(names[i]);
                }
            }
            return v.toArray(new String[v.size()]);
        }

调用给定文件名过滤器的accept方法。在您的示例中,字符串s是 names [i]
list()返回一个字符串数组,用于命名由文件路径名表示的目录中的文件和目录。

which calls the accept method of the given filename filter. String s is in your example names[i]. list() returns an array of strings naming the files and directories in the directory denoted by the files pathname.

解释您的代码:

String[] list = f.list(new FilenameFilter() {
    public boolean accept(File f, String s) {  
      return s.endsWith(".java");  
    }  
  }); 

使用FilenameFilter接口的新匿名类调用File类的列表方法(见上文)与accept方法的实现。

calls the list method of the File class (see above) with a new anonymous class of the FilenameFilter interface with an implementation of the accept method.

这篇关于匿名类Java问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆