向社区问好,我最近在我的 java 项目中遇到了序列化和反序列化的问题。我有一个类的对象,其中包含其他对象作为字段。
我想将对象的状态存储到字节数组中,然后反序列化字节数组并返回原始对象。但是,组成我的对象的对象对象的字段不可序列化(来自第三方库),因此必须首先将它们声明为 transient 。
现在我的对象已序列化和反序列化,但正如预期的那样,由于我之前提到的 transient 声明,它的字段为空。我尝试在我的序列化类中本地创建所有元素,并为它们分配原始值并继续该过程,但没有任何区别。我引用下面的部分代码,有什么想法吗?预先感谢:)
这是我的对象的类及其字段
public class AbePublicKey implements java.io.Serializable{
private static final long serialVersionUID = 7526472295622776147L;
public transient Element g;
public transient Element h;
public transient Element f;
public transient Element e_g_g_hat_alpha;
}
这是我的序列化器函数
public byte[] PublicKeytoByteArray(AbePublicKey publickey) throws IOException {
KeyAuthority keyauthority = new KeyAuthority();
byte[] bytes = null;
ByteArrayOutputStream bos = null;
ObjectOutputStream oos = null;
publickey.setElements(g, h, f, e_g_g_hat_alpha);
try {
bos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bos);
oos.writeObject(publickey);
oos.flush();
bytes = bos.toByteArray();
} finally {
if (oos != null)
oos.close();
}
if (bos != null) {
bos.close();
}
}
return bytes;
}
这是我的解串器函数
public static AbePublicKey PublicKeyBytestoObject(byte[] publickeybytes) throws IOException, ClassNotFoundException {
AbePublicKey obj = null;
ByteArrayInputStream bis = null;
ObjectInputStream ois = null;
try {
bis = new ByteArrayInputStream(publickeybytes);
ois = new ObjectInputStream(bis);
obj = (AbePublicKey) ois.readObject();
} finally {
if (bis != null) {
bis.close();
}
if (ois != null) {
ois.close();
}
}
return obj;
}
最佳答案
如果您想要控制对象的序列化方式,请实现Externalized 接口(interface)以及关联的readExternal 和writeExternal 方法。这使您可以完全控制对象的序列化方式。
显然,您无法序列化包含不可序列化字段的类。但您也许可以编写足够的数据来自行重新创建对象。
关于java - 如何将内部没有可序列化字段的java对象序列化为字节数组并反序列化该数组以获得原始对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39649351/