今天碰到一個(gè)很奇怪的問題,是從數(shù)據(jù)庫中取某個(gè)時(shí)間類型字段的值,需要把它轉(zhuǎn)成string型,然后問題就出來了,因?yàn)檫@個(gè)字段可能存在空值,斷點(diǎn)后走到轉(zhuǎn)string型這行就報(bào)錯(cuò)。一直沒想明白,后來老大跑過來瞄了幾眼就指出了問題所在。高人就是高人啊!
由于從數(shù)據(jù)庫讀到的空字段=null的,所以當(dāng)我toString()的時(shí)候肯定會(huì)報(bào)錯(cuò)。舉個(gè)例子:
public class test{
public test(){
Object s = null; //這比作字段的值
String s1 = s.toString(); //報(bào)錯(cuò)
System.out.println (s1);
}
public static void main(String[] a){
new test();
}
}
解決的辦法就是寫一個(gè)方法將所有為NULL的值賦為空
public class test{
public test(){
Object s = null;
String s1 = this.strSafe(s);
System.out.println (s1); }
public static void main(String[] a){
new test();
}
public String strSafe(Object obj){
if(obj == null)
obj="";
return obj.toString();
}
}
最近我感覺越來越遲鈍了,想個(gè)很簡單的for循環(huán)就要想老半天。郁悶啊,等發(fā)錢了買腦輕松去了