0

当我尝试通过套接字发送此类时,我得到的只是 NullPointException。我将如何做到这一点,以便我不会得到 NullPoint 异常?

public class Hick implements Serializable{
public JTextArea jta;
public Hick(){
jta = new JTextArea();
}
}
4

1 回答 1

1

我用以下代码对其进行了测试,它似乎工作正常......

我会确保您可以先在本地序列化对象以排除任何潜在问题。如果您仍然无法通过套接字加载它,那么您的套接字代码有问题,而不是序列化

public class TestSerialisation {

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

    public TestSerialisation() {
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;
        Wrapper out = new Wrapper();
        System.out.println("Before = " + out.dump());
        try {
            try {
                oos = new ObjectOutputStream(new FileOutputStream(new File("Test.out")));
                oos.writeObject(out);
            } finally {
                try {
                    oos.close();
                } catch (Exception e) {
                }
            }

            Wrapper in = null;
            try {
                ois = new ObjectInputStream(new FileInputStream(new File("Test.out")));
                in = (Wrapper) ois.readObject();
            } finally {
                try {
                    ois.close();
                } catch (Exception e) {
                }
            }            
            System.out.println("After = " + (in == null ? "null" : in.dump()));            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
    }

    public static class Wrapper implements Serializable {

        private JTextArea textArea;

        public Wrapper() {
            textArea = new JTextArea("I'm some text");
        }

        public String dump() {
            return textArea.getText();
        }
    }
}

还要确保您运行的是兼容版本的 Java,并且(如果我没记错的话)两端都有兼容版本的序列化对象。

于 2012-11-11T08:12:24.817 回答