I am currently experimenting with sending serialized objects over sockets in Java, and I have come across a scenario where I am trying to send an object containing data to a client whose class definition matches the server's other than the client's definition implements an abstract method (the method isn't even declared in the server's class definition).
Client Command class definition
package lol;
import java.io.Serializable;
public abstract class Command implements Serializable
{
public static final long serialVersionUID = 1;
public final String[] args;
public Command(String[] args)
{
this.args = args;
}
public abstract void execute();
}
Client Print class definition
package lol;
public class Print extends Command
{
public Print(String[] args)
{
super(args);
}
@Override
public void execute()
{
System.out.println(args[0]);
}
}
Client main class
package client;
import lol.Command;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;
public class Client
{
private static Socket s = null;
public static void main(String[] args) throws IOException, ClassNotFoundException
{
s = new Socket("127.0.0.1", 1000);
System.out.println("[*] Connected to host " + s.getInetAddress());
ObjectInputStream in = new ObjectInputStream(s.getInputStream());
Command command = (Command) in.readObject();
command.execute();
s.close();
}
}
Server Command class definition
package lol;
import java.io.Serializable;
public class Command implements Serializable
{
public static final long serialVersionUID = 1;
public final String[] args;
public Command(String[] args)
{
this.args = args;
}
}
Server Print class definition
package lol;
public class Print extends Command
{
public Print(String[] args)
{
super(args);
}
}
Server main class
package server;
import lol.Command;
import lol.Print;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server
{
private static ServerSocket ss = null;
public static void main(String[] args) throws IOException
{
ss = new ServerSocket(1000);
Socket s = ss.accept();
ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());
out.writeObject(new Print(new String[]{"hi!"}));
s.close();
ss.close();
}
}
As you can see, there is really no need for me to implement execute() in the server as it will never be called, and the object is instead used to invoke a method on the client, however the class definitions do not match and so I have to set a custom serialVersionUID. Is this a bad practice in the world of software development? If so, what alternatives can I use?