Java 7 - LinkOption - why is NOFOLLOW_LINKS the only available option?
Asked Answered
B

3

7

I think the title says it all. How would I specify FOLLOW_LINKS? Why create an enum with just one option? For example, the method java.nio.file.Files.getLastModifiedTime(Path, LinkOption...) takes an array of LinkOption-s as argument. You have to pass something, yet you can only pass the one option available. This surprised me, and would like to know more about it.

Bowerman answered 18/11, 2013 at 16:22 Comment(1)
Of course, allowing an arbitrary number of options allows future extensions without the need to change the API.Cothurnus
P
4

Following links is the default behavior. I.e., if you don't specify NOFOLLOW_LINKS, then links are followed.

From the documentation of the Files.getLastModifiedTime() method (emphasis mine):

The options array may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed and the file attribute of the final target of the link is read. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.

Palladian answered 18/11, 2013 at 16:29 Comment(3)
yes, i figured so after a while looking around into other nio areas, i found "When copying a symbolic link, the target of the link is copied. If you want to copy the link itself, and not the contents of the link, specify either the NOFOLLOW_LINKS or REPLACE_EXISTING option." which explains the presence of LinkOption enum. I don't know why I have not checked the docs for Files.getLastModifiedTime() first.Wachtel
It does seem like it would have been beneficial if the LinkOption documentation mentioned that following links is the default behavior for calls where LinkOption is used.Palladian
another problem is that when i looked at the javadocs for getLastModifiedTime() I didn't read the "executive summary" at the top, just jumped directly to Parameters section, and all it says there is: "options - options indicating how symbolic links are handled" And so I could not understand why my only option seems to be to NOT follow symlinks. All clear now :-) ThanksWachtel
N
1

What confused me a bit is that the LinkOptions argument to Files.exists() is a vararg argument , a fact I did not recognize immediately... you may just leave it away. Setting it to null will give an exception.

Nadenenader answered 8/11, 2014 at 5:24 Comment(0)
D
1

Many of the NIO.2 methods use a varargs for passing options, even when there is only one enum value available. The advantage of this approach, as opposed to say just passing a boolean argument, is future-proofing. These method signatures are insulated from changes in the Java language down the road when future options are available.

cited from "OCP Oracle Certified Professional Java SE 11 Programmer II"

Dangerous answered 26/11, 2020 at 13:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.