这里我有两个类ClientToSendCalculable.java

    import java.io.*;
import java.net.*;

public class ClientToSendCalculable implements Serializable
{
    public ClientToSendCalculable(int port)
    {
        try
        (
            Socket s = new Socket("localhost", port);
            ObjectOutputStream writer = new ObjectOutputStream(s.getOutputStream());
            ObjectInputStream reader = new ObjectInputStream(s.getInputStream());
        )
        {
            System.out.println("Connection was established!");

            ClientToSendCalculable.Addition addition = new ClientToSendCalculable.Addition();
            addition.firstAddendum = 5;
            addition.secondAddendum = 7;

            writer.writeObject(addition);
            double res = (Double)reader.readObject();

            System.out.println(res);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    private class Addition implements Calculable, Serializable
    {
        private double firstAddendum, secondAddendum;

        public double calc()
        {
            return firstAddendum + secondAddendum;
        }
    }

    public static void main(String[] args)
    {
        new ClientToSendCalculable(7777);
    }
}


和ServerToGetCalculable.java

import java.io.*;
import java.net.*;

public class ServerToGetCalculable
{
    public ServerToGetCalculable(int port)
    {
        try
         (
             ServerSocket ss = new ServerSocket(port);
             Socket s = ss.accept();
             ObjectOutputStream writer = new ObjectOutputStream(s.getOutputStream());
             ObjectInputStream reader = new ObjectInputStream(s.getInputStream());
         )
        {
            System.out.println("Got a client!");

            Calculable calcObj = (Calculable)reader.readObject();
            double res = calcObj.calc();

            writer.writeObject(res);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    public static void main(String[] args)
    {new ServerToGetCalculable(7777);}
}


我的问题是ClientToSendCalculable.java为什么要实现Serializable?我只通过Socket发送其内部类Addition.java,但没有单独发送ClientToSendCalculable.java。这就是为什么在我看来,仅Addition.java是可序列化的就足够了,但是如果我将ClientToSendCalculable.java设置为不是可序列化的,我将得到一个异常,试图执行以下代码行:

writer.writeObject(addition);

最佳答案

Addition.java是一个内部类(非静态)->它包含一个字段,该字段保存对封闭的ClientToSendCalculable实例的引用->该外部类的字段必须进行序列化->它必须实现Serializable接口。

09-11 19:20
查看更多