The exception of the null pointer is disgusting, I am afraid is the actual application of the most frequently occurring anomalies, the following is how to avoid nullpointerexception appearance of the technique
- Before using an object, it is best to know if they are possible null, and if not, use the IF statement to determine whether to use an object, or to traverse a collection, you need to make sure that they are non-empty. It's a rule that works in any situation.
Object obj = service.getobj (); return obj.getsomefiled (); // null pointer exception appears
- The fields in the database are best set to be non-empty, that is, the default value is set, and objects accepted from the front end are also sentenced to null processing.
- It is a good idea to determine whether an object is empty until the underlying type is compared to the underlying type, unless you can fully guarantee that they are non-empty, that is, if the object is empty when unpacking automatically, for example:
Integer count=obj.getcount (); if (0 < count) { ... // null pointer exception appears }
Use the Apache Lang Package tool class to convict empty and non-empty: StringUtils and Collectionutils
if (Stringutils.isnotempty ()) { ...}
Avoiding NullPointerException in Java development