我正在试图在java中实现serializable,但我得到了一个例外。
这是我的可序列化类:
public class Serialize implements java.io.Serializable {
private static final long serialVersionUID = 1L;
public double dis1;
public double dis2;
public double error1;
public double error2;
public double coorx;
public double coory;
public double coorz;
}
当我创建这个类的对象并尝试转换为字节时。
Serialize serial = new Serialize();
serial.dis1 = dis1;
serial.dis2 = dis2;
serial.error1 = error1;
serial.error2 = error2;
serial.coorx = coorx;
serial.coory = coory;
serial.coorz = coorz;
byte[] bytes = null;
int length = 0;
try {
ByteArrayOutputStream bs = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(bs);
os.writeObject(serial); ///EXCEPCION
os.close();
bytes = bs.toByteArray();
length = bytes.length;
} catch (IOException e) {
e.printStackTrace();
}
我做错了什么?
logcat的:
04-24 09:15:29.734: W/System.err(4279): java.io.NotSerializableException: org.gradiant.sistole.locservice.Communication
04-24 09:15:29.734: W/System.err(4279): at java.io.ObjectOutputStream.writeNewObject(ObjectOutputStream.java:1364)
04-24 09:15:29.734: W/System.err(4279): at java.io.ObjectOutputStream.writeObjectInternal(ObjectOutputStream.java:1671)
04-24 09:15:29.734: W/System.err(4279): at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1517)
04-24 09:15:29.734: W/System.err(4279): at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1481)
04-24 09:15:29.734: W/System.err(4279): at java.io.ObjectOutputStream.writeFieldValues(ObjectOutputStream.java:979)
04-24 09:15:29.734: W/System.err(4279): at java.io.ObjectOutputStream.defaultWriteObject(ObjectOutputStream.java:368)
04-24 09:15:29.734: W/System.err(4279): at java.io.ObjectOutputStream.writeHierarchy(ObjectOutputStream.java:1074)
04-24 09:15:29.734: W/System.err(4279): at java.io.ObjectOutputStream.writeNewObject(ObjectOutputStream.java:1404)
04-24 09:15:29.734: W/System.err(4279): at java.io.ObjectOutputStream.writeObjectInternal(ObjectOutputStream.java:1671)
04-24 09:15:29.734: W/System.err(4279): at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1517)
04-24 09:15:29.734: W/System.err(4279): at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1481)
04-24 09:15:29.734: W/System.err(4279): at org.gradiant.sistole.locservice.Communication.datarequest(Communication.java:447)
04-24 09:15:29.734: W/System.err(4279): at org.gradiant.sistole.locservice.UWBmain.process(UWBmain.java:311)
04-24 09:15:29.734: W/System.err(4279): at org.gradiant.sistole.locservice.UWBmain$2.run(UWBmain.java:279)
04-24 09:15:29.734: W/System.err(4279): at java.lang.Thread.run(Thread.java:841)
感谢
答案 0 :(得分:0)
看起来你试图序列化类org.gradiant.sistole.locservice.Communication的对象,这是你尝试序列化的类中的一个对象吗?如果是这样,那个对象也应该实现serializable来序列化对象。如果你不需要这个对象,你可以像以下那样使它成为瞬态:
transient Communication comm = new Communication(...);
此对象不会被序列化,如果您反序列化该对象,它将为null。
如果你无法实现serializable,并且在反序列化时确实需要它,那么你必须找到一种在反序列化时重建对象的方法。