无法存储非序列化对象的引用

时间:2013-12-22 17:39:53

标签: java serialization

您好团队最近我已经开始使用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());超过这一行我得到了null pointer.please如果可能的话代替代码。

提前致谢。

1 个答案:

答案 0 :(得分:1)

如果要存储Identity的Address对象,则必须删除transient并创建地址Serializable,以便在序列化Identity对象时不会获得NotSerializableException