见下面的程序,这个回调是怎么发生的啊?从程序中怎么看不出逻辑,都没有调用accept ()?
import java . io . File ;
import java . io . * ;
import java . util . * ;
import java . util . regex . * ;
public class DirList
{
public static void main (String [ ] args)
{
File path = new File (".") ;
String[ ] list ;
if ( args . length == 0 )
{
list = path . list ( ) ;
}
else
{
list = path . list (new DirFilter ( args [ 0 ])) ;
}
Arrays . sort (list , String . CASE_INSENSITIVE_ORDER );
for (String dirItem : list )
System . out . println (dirItem) ;
}
}
class DirFilter implements FilenameFilter
{
private Pattern pattern ;
public DirFilter ( String regex )
{
pattern = pattern . compile ( regex );
}
public boolean accept ( File dir , String name )
{
return pattern . matcher ( name ) . matches ( ) ;
}
}
Simply put, it happens using the conditions defined in your filter when you add it to the list
accept
方法在file.list
里面调用的,楼主可以打开File
类的源代码,很清楚的看到调用流程,下面是我从File
类里面复制出来的list
methodThe meaning of callback is that you implement an interface (not necessarily an interface), but do not call this interface, but let the party that defines this interface (here should refer to the Java class library) to call the implementation you gave .
The operation of listing subdirectories that meet the requirements involves several steps, some of which are unchanged (for example, you need to first get all the subdirectories in the current directory. I have not seen the source code, but it should be a system call of the OS) , these are all implemented in the Java class library. Corresponding to this step is the change operation, that is, what conditions do you want the subdirectory to meet. Therefore, the class library designs the changed part as an interface for you to implement, and then you register your callback through
File.list()
.File.list()
去注册你的回调。因为你不调用,所以才叫回调呀 - don't call me, I'll call back
或者更直接一点,
Because you don't call, that's why it's called callback - don't call me, I'll call back#🎜🎜#accept(File, String)
的调用发生在File.list(FilenameFilter)
函数内。在函数内,会将参数dir
和name
传递给你给的实现,也就是调用accept(File, String)
#🎜🎜#Or more directly, the call of
accept(File, String)
occurs within theFile.list(FilenameFilter)
function. Within the function, the parametersdir
andname
will be passed to the implementation you gave, that is, theaccept(File, String)
method will be called. #🎜🎜#