我的代碼如下拋出java.io.NotSerializableException。爲什麼?謝謝!將對象轉換爲字節數組拋出NotSerializableException
private void test3() {
Element3 element3=new Element3();
ObjectToBytes3(element3);
}
private class Element3 implements Serializable{
int code=0;
}
//-----------------------------------
private void ObjectToBytes3(Element3 elem){
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = null;
try {
out = new ObjectOutputStream(bos);
out.writeObject(elem);
byte[] myBytes = bos.toByteArray();
}
catch (Exception e) {myPrint("exception",e.toString());}
finally {
try{
out.flush();
out.close();
bos.close();
}
catch (Exception e) {}
}
}
輸出和堆棧如下: 2674,25 ObjToBytes: 2674,32異常:java.io.NotSerializableException:java.util.concurrent.ThreadPoolExecutor中堆棧= java.io.NotSerializableException:JAVA .util.concurrent.ThreadPoolExecutor 在java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1164) 在java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1518) 在java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream中。 java:1483) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1400) 在java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1158) 在java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1518) 在java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1483) 在java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1400) 在java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1158) 在java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:330)
這很有趣,但下面的代碼工作好嗎
================================
class My implements Serializable{
byte a=1;
int b=88;
String s="ggg";
private My(byte a1, int b1,String s1) {
a=a1;
b=b1;
s=s1;
}
}
private void test() {
My my=new My((byte)5,10,"jjj");
ObjectToBytesTest(my);
}
//-----------------------------------
private void ObjectToBytesTest(My my){
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = null;
try {
out = new ObjectOutputStream(bos);
out.writeObject(element);
byte[] myBytes = bos.toByteArray();
}
catch (Exception e) {print("exception",e.toString());}
finally {
try{
out.flush();
out.close();
bos.close();
}
catch (Exception e) {}
}
}
你的代碼工作正常。可能你在這段代碼中沒有問題。顯示完整堆棧跟蹤 –
[Java Serializable Object to Byte Array]可能的重複(http://stackoverflow.com/questions/2836646/java-serializable-object-to-byte-array) – EJP