[英]Java: ObjectOutputStream with Serializable problem
I have these three classes: 我有以下三个课程:
Command: 命令:
package pack;
public abstract class Command impements java.io.Serializable
{
public abstract void execute();
}
Client: 客户:
package pack;
// imports....
public class Client
{
Socket socket;
// Constructor...
public void sendCommand(Command c)
{
try
{
new ObjectOuputStream(socket.getOutputStream()).writeObject(c);
} catch (Exception e) {e.printStackTrace()};
}
}
MyKeyListener: MyKeyListener:
This keylistener is added to a component in a JFrame. 此关键侦听器已添加到JFrame中的组件。
public class MyKeyListener implements KeyListener
{
private Client client;
public MyKeyListener(Client c)
{ client = c; }
public void keyTyped(....)......; // This method does nothing
public void keyPressed(KeyEvent e)
{
client.sendCommand(new Command() {
public void execute()
{
new Robot().keyPress(e.getKeyCode());
}
});
}
// The same for keyRelease()....
}
The problem is: if I run the code and he wants to send a Command. 问题是:如果我运行代码,而他想发送命令。 The streams stops writing because "MyKeyListener is not Serializable" ???!! 流停止写入,因为“ MyKeyListener不可序列化”? But I never try to send MyKeyListener
但是我从不尝试发送MyKeyListener
Nested classes in Java actually don't exist at the byte code level - the compiler fakes them by inserting hidden fields, access methods and constructors. Java中的嵌套类实际上在字节码级别上不存在-编译器通过插入隐藏字段,访问方法和构造函数来伪造它们。 In your case, the anonymous subclass of Command
probably has a compiler-generated reference to the MyKeyListener
instance in which it was created, even if that reference is not used for anything. 在您的情况下, Command
的匿名子类可能具有编译器生成的对创建它的MyKeyListener
实例的引用,即使该引用未用于任何事情。
To fix this, use a top-level subclass of Command instead of an anonymous class. 若要解决此问题,请使用Command的顶级子类而不是匿名类。
提示:尝试在(匿名)命令类execute()方法中键入MyKeyListener.this.toString()。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.