java.nio.file: Where is the Path interface actually implemented?

百般思念 提交于 2019-12-05 14:05:14

问题


Recently I was doing some coding using the java.nio.file package introduced in Java 7 and saw an example using Path like this:

Path path = Paths.get("C:\\Users");

Given that Path is an interface I was confused on how you could have a reference to it, however after some research I found out that a reference to an interface is allowed but it must point to a class that implements the interface. Looking on from this I looked at the Paths class and saw that it didn't implement Path. Looking at the source code the actual method Paths.get method is as follows:

public static Path get(String first, String... more) {
    return FileSystems.getDefault().getPath(first, more);
}    

the method first returns an object of type FileSystem (from an abstract class I think) using what I believe is called a static factory method, but FileSystem also doesn't implement the interface.

My question is does anyone know/able to explain where the Path interface is actually implemented as I cannot seem to find where this occurs.


回答1:


If you look carefully you will notice that the method getPath from FileSystem object returns implementation of Path interface. By invoking FileSystems.getDefault() you will retrieve implementation of FileSystem interface which will depend on system. On Linux system you will get LinuxFileSystem object witch extends UnixFileSystem class.

You can look for example at UnixFileSystem class from openjdk which is implementation of FileSystem interface.

Here is the link with implementation of getPath method from UnixFileSystem, which will return instance of UnixPath.

You must remember that FileSystems.getDefault return implementation dependent on the operating system. Furthermore source code of those classes isn't available in oracle jdk.




回答2:


Inside NetBeans IDE, you can view the implementation details of Paths class by doing the following:

  • Step one:

    click your cursor on the line where you have written your Path code. An example Path would be:

Path p = Paths.get("someDir\someOtherDir");

  • Step Two:

Click Debug | Step Into (F7)

It will bring up the implementation details of Paths



来源:https://stackoverflow.com/questions/20836121/java-nio-file-where-is-the-path-interface-actually-implemented

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!