我想使用ByteArrayOutputStream
java序列化一个类:
public void serializ(UniqueTag m) throws IOException {
ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
ObjectOutputStream stream = new ObjectOutputStream(byteOutput);
stream.writeObject(m);
stream.flush();
stream.close();
byteOutput.flush();
byteOutput.close();
}
一个类想要序列化:
import java.io.Serializable;
public class UniqueTag implements Comparable<UniqueTag>, Serializable {
public final static UniqueTag MIN = new UniqueTag(Integer.MIN_VALUE,
Integer.MIN_VALUE);
public final static UniqueTag MAX = new UniqueTag(Integer.MAX_VALUE,
Integer.MAX_VALUE);
private final int replicaId;
private final int counter;
public static UniqueTagGenerator createGenerator() {
return new UniqueTagGenerator() {
int currentStamp;
@Override
public UniqueTag nextTag(final int replicaId) {
return new UniqueTag(replicaId, currentStamp++);
}
};
}
public UniqueTag(final int replicaId, final int counter) {
this.replicaId = replicaId;
this.counter = counter;
}
public int getReplicaId() {
return replicaId;
}
public int getCounter() {
return counter;
}
@Override
public int compareTo(UniqueTag o) {
if (replicaId != o.replicaId) {
return replicaId - o.replicaId;
}
return counter - o.counter;
}
public UniqueTag clone() {
return new UniqueTag(replicaId, counter);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof UniqueTag))
return false;
final UniqueTag other = (UniqueTag) obj;
return counter == other.counter && replicaId == other.replicaId;
}
@Override
public String toString() {
return "(" + replicaId + "," + counter + ")";
}
}
我有这个错误:
Exception in thread "main" java.io.NotSerializableException: jbenchmarker.treedoc.UniqueTag$1
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1164)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1518)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1483)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1400)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1158)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1518)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1483)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1400)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1158)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:330)
请问哪里有问题?我序列化一个类,但它向我显示一个错误!:(