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

2

18

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.

Vexillum answered 30/12, 2013 at 8:44 Comment(3)
System.out.println(path.getClass());Plimsoll
If you use IDE like Eclipse, you can use Show type hierarchy feature. help.eclipse.org/juno/…Entitle
getPath() returns a reference to an object that implements Path.Janik
C
15

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.

Creditor answered 30/12, 2013 at 11:5 Comment(2)
How to fix those missing source code in oracle jdk?Polycarp
@iamprem: I don't think you can. Check out openjdk instead.Lawson
C
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

Carty answered 31/3, 2015 at 14:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.