Java: ObjectOutputStream with Serializable problem
-
05-07-2019 - |
Question
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:
This keylistener is added to a component in a 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" ???!! But I never try to send MyKeyListener
Solution
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. 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.
To fix this, use a top-level subclass of Command instead of an anonymous class.
OTHER TIPS
Hint: Try typing MyKeyListener.this.toString() in the (anonymous) Command class execute() method.