Java 如何正确返回方法的 Optional<>?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37811794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to properly return Optional<> of a method?
提问by Nimrod
I have read a lot of Java 8 Optional and I do understand the concept, but still get difficulties when trying to implement it myself in my code.
我已经阅读了很多 Java 8 Optional 并且我确实理解这个概念,但是在尝试在我的代码中自己实现它时仍然遇到困难。
Although I have serached the web for good examples, I didn't found one with good explanation.
虽然我已经在网上搜索了很好的例子,但我没有找到一个很好的解释。
I have the next method:
我有下一个方法:
public static String getFileMd5(String filePath) throws NoSuchAlgorithmException, IOException {
AutomationLogger.getLog().info("Trying getting MD5 hash from file: " + filePath);
MessageDigest md = MessageDigest.getInstance("MD5");
InputStream inputStream;
try {
inputStream = Files.newInputStream(Paths.get(filePath));
} catch (NoSuchFileException e) {
AutomationLogger.getLog().error("No such file path: " + filePath, e);
return null;
}
DigestInputStream dis = new DigestInputStream(inputStream, md);
byte[] buffer = new byte[8 * 1024];
while (dis.read(buffer) != -1);
dis.close();
inputStream.close();
byte[] output = md.digest();
BigInteger bi = new BigInteger(1, output);
String hashText = bi.toString(16);
return hashText;
}
This simple method returns the md5 of a file, by passing it the file path. As you can notice, if the file path doesn't exists (or wrong typed) a NoSuchFileExceptionget thrown and the method return Null.
这个简单的方法通过将文件路径传递给文件来返回文件的 md5。如您所见,如果文件路径不存在(或输入错误),则会抛出NoSuchFileException并且该方法返回Null。
Instead of returning null, I want to use Optional, so my method should return Optional <String>
, right?
我想使用 Optional 而不是返回 null,所以我的方法应该返回Optional <String>
,对吗?
- What is the proper way of doing it right?
- If the returned String is null - can I use here
orElse()
, or this kind of method should be used by the client side?
- 正确的做法是什么?
- 如果返回的字符串为空 - 我可以在这里使用
orElse()
,还是客户端应该使用这种方法?
采纳答案by Joop Eggen
Right.
对。
public static Optional<String> getFileMd5(String filePath)
throws NoSuchAlgorithmException, IOException {
return Optional.empty(); // I.o. null
return Optional.of(nonnullString);
}
Usage:
用法:
getFileMd5(filePath).ifPresent((s) -> { ... });
or (less nice as undoing the Optional)
或(不如撤消 Optional 好)
String s = getFileMd5(filePath).orElse("" /* null */);