Java NotSerializableException:

时间:2014-06-02 23:29:58

标签: java serialization serializable

我收到以下错误:

java.io.NotSerializableException: cscie55.project.AccountInfo

我的AccountInfo类没有实现java.io.Serializable.我是否必须实现Serializable?

如果是这样,有人可以帮我解决这个问题吗?

以下是我的客户端类的一部分:

public class Client extends UnicastRemoteObject implements ATMListener {

    public Client() throws RemoteException {

    }

    private static AccountInfo getAccountInfo(int accountNumber, int pin) {
        //AccountInfo accountInfo = new AccountInfo(accountNumber, pin);
        return new AccountInfo(accountNumber, pin);
    }

    public static void main(String[] args) {
        ATM atm;

        try {
            ATMFactory factory = (ATMFactory)Naming.lookup("atmfactory");
            atm = factory.getATM();
            Client clientListener = new Client();
            atm.addListener(clientListener);
            Client.testATM(atm);
        } catch (MalformedURLException mue) {
            mue.printStackTrace();
        } catch (NotBoundException nbe) {
            nbe.printStackTrace();
        } catch (UnknownHostException uhe) {
            uhe.printStackTrace();
        } catch (RemoteException re) {
            re.printStackTrace();
        }

    }

AccountInfo类:

public final class AccountInfo {

    private final int accountNumber;
    private final int pin;

    public AccountInfo(int accountNumber, int pin) {
        this.accountNumber = accountNumber;
        this.pin = pin;
    }

    public int getAccountNumber() {
        return accountNumber;
    }

    public int getPin() {
        return pin;
    }

}

帐户在BankImpl类中创建:

public class BankImpl extends UnicastRemoteObject implements Bank {

    public static LinkedHashMap<Integer, Account> accounts;

    public BankImpl() throws RemoteException {

        accounts = new LinkedHashMap<Integer, Account>();

        //constructor creates 3 accounts
        Account account1 = new Account(0000001, 1234, 0, true, true, true);
        Account account2 = new Account(0000002, 2345, 100, true, false, true);
        Account account3 = new Account(0000003, 3456, 500, false, true, true);

        //assigns all the accounts to a collection
        accounts.put(0000001, account1);
        accounts.put(0000002, account2);
        accounts.put(0000003, account3);
    }

2 个答案:

答案 0 :(得分:3)

使您的AccountInfo类实现Serializable:

public final class AccountInfo implements Serializable {

您不需要添加任何其他方法,但为了安全起见,您应该在AccountInfo类中定义serialVersionUID:

private static final long serialVersionUID = insert_random_long_here;

您可以使用此网站生成随机serialVersionUID:http://random.hd.org/getBits.jsp?numBytes=0&type=svid

答案 1 :(得分:1)

  

我的AccountInfo类没有实现java.io.Serializable。我必须序列化吗?

不,但您的问题表明您正在序列化它。我认为你的意思是“我必须做到Serializable?。答案是“是”&#39;,如果您打算序列化它。

如果它被序列化并且您不希望序列化,请在序列化的对象中引用它transient

注意UnicastRemoteObject是服务器,而不是客户端。