How can one create a java.nio.Path that represents no path no matter the environment?
I cannot call Path.of(<String>)
and guarantee the resulting path to point to an invalid file or directory.
What I'm looking for is if there is a safer way to represent an empty / invalid path than using a null
value.
Depending on your use case, there are a couple options:
Optional<Path>
and return Optional.empty()
to denote no path.I wouldn't really try to create an invalid Path
. It is not intended to be used that way. If you have a function that could return a Path
, but in certain cases it would not, the best approach is to return Optional<Path>
.
The advantage is that you will be forcing whoever is calling the function to check for the case where there is no valid Path
. Unlike returning null
, where if the caller forgets to check for it, he will just get the program blow up with a NullPointerException
later on.
如果您想避免空值,请使用 Optional,然后您可以测试空值/存在。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.