gpt4 book ai didi

java - 无法存储不可序列化对象的引用

转载 作者:太空宇宙 更新时间:2023-11-04 07:10:26 25 4
gpt4 key购买 nike

嗨,团队最近我开始使用 I/O 包,但遇到了一个问题,如下面的代码所示,我有一个类 Identity,其中包含非序列化类 Address 的引用。我想将地址对象与身份类一起存储,但在读取该对象时,我无法取回地址对象,并且它在我的主类中引发空指针异常下面我显​​示了与我的问题相关的所有代码,请执行必要的操作。

Address class--

package com.io.practice;
public class Address {

String state;
String country;

public String getState() {
return state;
}

public void setState(String state) {
this.state = state;
}

public String getCountry() {
return country;
}

public void setCountry(String country) {
this.country = country;
}

}


Identity Class--

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import com.io.practice.Address;

public class Identity implements Serializable {

private static final long serialVersionUID = 1L;
transient Address address;
int panCardId;

public Address getAddress() {
return address;
}

public void setAddress(Address address) {
this.address = address;
}

public int getPanCardId() {
return panCardId;
}

public void setPanCardId(int panCardId) {
this.panCardId = panCardId;
}

public void writeObject(ObjectOutputStream os) throws IOException {
os.defaultWriteObject();
os.writeObject(address);

}

public void readObject(ObjectInputStream is) throws IOException, ClassNotFoundException {
is.defaultReadObject();
this.address=(Address) is.readObject();
}

}

GraphTest main class--

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import com.io.practice.Address;

public class GraphTest {

public static void main(String[] args) throws IOException, ClassNotFoundException {
Identity id = new Identity();
Address add = new Address();
add.setCountry("Austrialia");
add.setState("Sidney");
id.setPanCardId(560100);
id.setAddress(add);
FileOutputStream fileOut = new FileOutputStream("D:/cgi.ser");
ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);
objectOut.writeObject(id);
objectOut.flush();
objectOut.close();
FileInputStream fileIn = new FileInputStream("D:/cgi.ser");
ObjectInputStream objectIn = new ObjectInputStream(fileIn);
Identity identity = (Identity) objectIn.readObject();
System.out.println(identity.getPanCardId());
System.out.println(identity.getAddress().getCountry());

}

}

System.out.println (identity.getAddress().getCountry()); 在这一行上得到空指针。如果可能,请更正代码。

提前致谢。

最佳答案

如果您想存储 Identity 的 Address 对象,则必须删除 transient 并将 Address 设置为 Serialized,这样在序列化 Identity 对象时就不会出现 NotSerializedException

关于java - 无法存储不可序列化对象的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20732144/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com