标签:translate 判断 font 传递 number tar string www 默认
1) 从已知的String对象中调用equals()和equalsIgnoreCase()方法,而非未知对象。public static void main(String[] args) {
Object o = null;
String s = String.valueOf(o); -- 不会出空指针
s = o.toString(); -- 空指针
System.out.println(s);
}
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
3) 使用null安全的方法和库 有很多开源库已经为您做了繁重的空指针检查工作。其中最常用的一个的是Apache commons 中的StringUtils。你可以使用StringUtils.isBlank(),isNumeric(),isWhiteSpace()以及其他的工具方法而不用担心空指针异常。
StringUtils方法是空指针安全的,他们不会抛出空指针异常
System.out.println(StringUtils.isEmpty(
null
));
System.out.println(StringUtils.isBlank(
null
));
System.out.println(StringUtils.isNumeric(
null
));
System.out.println(StringUtils.isAllUpperCase(
null
));
4) 避免从方法中返回空指针,而是返回空collection或者空数组。
这个Java最佳实践或技巧由Joshua Bloch在他的书Effective Java中提到。这是另外一个可以更好的使用Java编程的技巧。通过返回一个空collection或者空数组,你可以确保在调用如size(),length()的时候不会因为空指针异常崩溃。Collections类提供了方便的空List,Set和Map: Collections.EMPTY_LIST,Collections.EMPTY_SET,Collections.EMPTY_MAP。这里是实例。
public
List getOrders(Customer customer){
List result = Collections.EMPTY_LIST;
return
result;
}
你同样可以使用Collections.EMPTY_SET和Collections.EMPTY_MAP来代替空指针。
标签:translate 判断 font 传递 number tar string www 默认
原文地址:http://www.cnblogs.com/duenboa/p/6665339.html