[英]Why a java interface returns itself <java.nio.file.Path>
為什么Java接口會返回自身?
我正在閱讀當前代碼
public class Find {
public static class Finder extends SimpleFileVisitor<Path>{
private final PathMatcher matcher;
private int numMatches = 0;
Finder(String pattern){
matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);
}
void find(Path file){
Path name = file.getFileName();
System.out.println("Name " + name);
if (name != null && matcher.matches(name)){
numMatches++;
System.out.println(file);
}
}
void done(){
System.out.println("Matched: " + numMatches);
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs){
find(file);
return CONTINUE;
}
查看file.getFileName(),它由一個接口表示
public interface Path
extends Comparable<Path>, Iterable<Path>, Watchable
但是返回值是您在行中看到的
System.out.println("Name " + name);
它必須是字符串,因為它是可打印的。
但是看一下界面
/**
* Returns the name of the file or directory denoted by this path as a
* {@code Path} object. The file name is the <em>farthest</em> element from
* the root in the directory hierarchy.
*
* @return a path representing the name of the file or directory, or
* {@code null} if this path has zero elements
*/
Path getFileName();
它返回一個Path對象,為什么這樣操作?
+
與至少一個類型為String
操作數一起使用時,是String
串聯運算符。 您將要研究toString()
方法。
+運算符廣泛用於打印語句。 例如:
String string1 = "saw I was "; System.out.println("Dot " + string1 + "Tod");
哪個打印
Dot saw I was Tod
這樣的串聯可以是任何對象的混合。 對於不是String的每個對象,將調用其toString()方法將其轉換為String。
基本上,所有引用類型都繼承Object
類,因此也繼承toString()
方法。 當您將String
和其他類型的引用串聯在一起時,將調用該類型的toString()
方法,並將所得的String
串聯起來。
此語句是錯誤的:
它必須是字符串,因為它是可打印的。
當使用變量代替String
,Java編譯器將隱式調用對象的toString()
方法(所有對象都具有)。 對於Path
,它將輸出Path
的字符串表示形式。 僅僅因為打印出文本並不意味着它是一個實際的String
實例。
Path getFileName()返回Path Object,因此,每當我們打印對象時,其toString()方法都將被調用,該方法是從Object類繼承的。
因此,調用了Path的toString()方法,並以字符串形式返回path對象。
所以做類似path.getFileName().getName();
事情 如果有這樣的方法來獲取名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.