Reputation: 31
How can I resolve the "NullPointerException" error in Java when accessing an object in a method?
Upvotes: 2
Views: 41
Reputation: 71
Java8 has added many new features, one of which is the Optional
class. The Optional
class has become part of the Java 8 class library and is used to solve the NullPointerException
.
Optional.of(T value)
Creates an Optional object containing a non-null value. If value is null, a NullPointerException
is thrown.
Optional.ofNullable(T value)
Creates an Optional object that may contain a null value. If value is null, returns an empty Optional object.
Optional.empty()
Creates an empty Optional object.
Optional<String> optional = Optional.of("Hello");
Optional<String> optionalNullable = Optional.ofNullable(null);
Optional<String> emptyOptional = Optional.empty();
You can find more usage of it in the doc.
Upvotes: 2
Reputation: 47
Check the object is null or enclose with try and catch
sol1: if(mainObject && mainObject.yourObject != null { /** add what yuo what you want to handle*/ }
Sol2: try{obj = mainObject.yourObject;}catch(Exception e){/** fallback code*/}
Upvotes: 1