我試圖來存儲所有的消息對象接受了一分鐘,一棵樹地圖和之後的一個分鐘的車一過,序列化和字節[]返回到另一個階級同時清除地圖,並開始儲存在下一分鐘收到的消息等等。獲取顯示java.lang.NullPointerException
public class StoreMessage extends Thread implements Serializable{
public static byte[] b=null;
public static Map <Long,Message> map1=Collections.synchronizedMap(new TreeMap<Long,Message>());
public static Calendar c1=Calendar.getInstance();
public static int year=c1.get(Calendar.YEAR);
public static int month=c1.get(Calendar.MONTH);
public static int day=c1.get(Calendar.DAY_OF_MONTH);
public static int hour=c1.get(Calendar.HOUR_OF_DAY);
public static int min=c1.get(Calendar.MINUTE);
public static GregorianCalendar gc = new GregorianCalendar(year, month, day, hour, min);
public static Date d=gc.getTime();
public static long time1=(d.getTime())/60000; //precision till minute of the time elapsed since 1 Jan 1970
public static long time2=time1+1;
public static byte[] store(Message message)throws Exception{
while(true)
{
if(time1<time2)
{
long preciseTime=TimeUnit.MILLISECONDS.toNanos(System.currentTimeMillis())+(System.nanoTime()-startNanotime);
map1.put(preciseTime, message);
}
else
{
b=Serializer.serialize(map1);
map1.clear();
time1=time2;
time2++;
return b;
}
}
}
}
爲什麼這個代碼給我空指針異常突出INT LEN = b.length個;的另一個類,它被稱爲返回值?
public static void record(Message message){
try{
//storing the serialized message in byte[]
byte[] b =StoreMessage.store(message);
int len=b.length; //<--highlights this line for null pointer exception
即使在進行修改後(即將返回放在else塊內),它也不會將控件返回給調用類。另外,沒有SOP語句(添加時)打印在else塊內部。爲什麼?
The Serializer class
public class Serializer {
//serializes an object and returns a byte array
public static byte[] serialize(Object map) throws IOException
{
ByteArrayOutputStream b = new ByteArrayOutputStream();
ObjectOutputStream o = new ObjectOutputStream(b);
o.writeObject(map);
return b.toByteArray();
}
//de-serialization of the byte array and returns an object
public static Object toObject (byte[] bytes)
{
Object obj = null;
try
{
ByteArrayInputStream bis = new ByteArrayInputStream (bytes);
ObjectInputStream ois = new ObjectInputStream (bis);
obj = ois.readObject();
}
catch (Exception ex) { }
return obj;
}
}
您的意思是把'的else分支外返回B'?它仍然被初始化爲'null',因爲首先if-branch將被執行。 – Howard 2012-04-07 12:56:26
您的StoreMessage.store(...)返回null,因爲b始終爲空。對不起,但它是可怕的代碼 - 爲什麼所有的靜態垃圾? – 2012-04-07 12:56:32
呃,我想'b'是空的。 – 2012-04-07 12:56:37