Search code examples
javaserializationserializable

Java NotSerializableException:


I am getting the following error:

java.io.NotSerializableException: cscie55.project.AccountInfo

My AccountInfo class doesn't implement java.io.Serializable. Do I have to make it Serializable?

If so, can someone help me with how to do it?

The following is part of my Client class:

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 class:

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;
    }

}

Accounts are created in BankImpl class:

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);
    }

Solution

  • Make your AccountInfo class implement Serializable:

    public final class AccountInfo implements Serializable {
    

    You don't need to add any other methods, however to be safe you should define a serialVersionUID in the AccountInfo class:

    private static final long serialVersionUID = insert_random_long_here;
    

    You can use this site to generate a random serialVersionUID: http://random.hd.org/getBits.jsp?numBytes=0&type=svid