I have found a new way to deal with NullPointerException in Java8, so I will write it as a reminder.
I will try to put out a slimy po.
java
public class Test {
public static void main(String[] args) {
String str = null;
System.out.print(str.length());
}
}
Processing result
Exception in thread "main" java.lang.NullPointerException
at Test.main(Test.java:6)
I got a NullPointerException. As a workaround implemented from java8, by adding Optional NullPointer can be dealt with. Change with the image below.
Action example
import java.util.Optional;
public class Test {
public static void main(String[] args) {
String str = null;
// System.out.print(str.length());
Optional<String> strOpt = Optional.ofNullable(str);
strOpt.ifPresent(v -> System.out.println(v.length()));
}
}
The process was completed without any NullPointerException.
ʻOptional` is implemented in java8 and later https://docs.oracle.com/javase/jp/8/docs/api/java/util/Optional.html
Optional<String> strOpt = Optional.ofNullable(str);
You can use the ʻofNullable () function by wrapping str with ʻOptional
.
As an argument to the ʻifPresentfunction Save the contents of
str to the variable
v` and use it in the System outline.
This method is called a lambda expression, and it is a new function implemented from java8 together with Optional.
strOpt.ifPresent(v -> System.out.println(v.length()));
and
get () `... (Added on 2020/07/31)At first I wrote the following example as a different pattern, but the following method seems to be *** a deadly workaround **. I will post it as a bad example with a commandment to myself. You can see it by reading this article https://qiita.com/BlueRayi/items/ef46496ef2ef36b9cbb7#%E3%81%AA%E3%82%8B%E3%81%B9%E3%81%8Foptionalifpresent%E3%82%82%E4%BD%BF%E3%81%86%E3%81%AA ( When you read this article, it seems that the Null check itself using Optional is nonsense in the first place.)
bad example
import java.util.Optional;
public class Test {
public static void main(String[] args) {
String str = null;
// System.out.print(str.length());
Optional<String> strOpt = Optional.ofNullable(str);
if(strOpt.isPresent()) {
String message = strOpt.get();
System.out.println(message.length());
}
}
}
Specifically, it is easy to implement the method of get () the value using isPresent () in the if statement. It is good to think that the isPresent () function is used when it is unavoidable because the merit of using Optional is not utilized, and the following article seems to be easy to understand in terms of nuance.
You should rarely use get. The purpose of using Optional is the message "If there is no value, please do it." If you suddenly get an exception using> get, it's the same as getting a NullPointerException.
https://irof.hateblo.jp/entry/2015/05/05/071450
Recommended Posts