0

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

1
  • I hope that the typos are not actually in your code. Commented Sep 11, 2009 at 16:32

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Hint: Try typing MyKeyListener.this.toString() in the (anonymous) Command class execute() method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.