Scenario
Wrapper classes come with a bunch of methods which are very easy to use in practice. When we literally assign a value to this kind of objects, these methods work well in a convenient and intuitive way. But if they take values from a SQL select result, they will become nullable objects when their corresponding fields in the database table are nulls. This causes a NullPointerException exception during runtime.
StringUtils can be used as an alternative to avoid the potential defect.
Example
import org.apache.commons.lang3.StringUtils;public class App{public static void main( String[] args ){String strA = "abcd";String strB = "ABcd";String strC = "abcd";String strNull = null;System.out.println( strB.replace("AB", "ab").equals(strA));try {strNull.equals(strA);} catch (NullPointerException ex) {System.out.println(ex);}System.out.println( StringUtils.equals(strA, strB) );System.out.println( StringUtils.equals(strA, strC) );System.out.println( StringUtils.equals(strNull, strA) );}}
Output:
truejava.lang.NullPointerException: Cannot invoke "String.equals(Object)" because "strNull" is nullfalsetruefalse
No comments:
Post a Comment