DEV Community

Discussion on: Copying objects of unknown class in Java requires using reflection. It's hideous.

Collapse
 
vilfrim profile image
vilfrim

You don't tell which part is your code and which is given but if you cannot create copies of commands for your history then maybe commands should support multiple previous states? And yes, it took way too much time from me to get this example to work and I do this for living:)

Collapse
 
wasimanitoba profile image
Wasim

Yep, no better way around it besides to require changes to the Command interface (our prof says the solution is for the Command to implement Cloneable)

Collapse
 
vilfrim profile image
vilfrim

Ok..I hope that your prof answered little bit longer than that because Cloneable interface is empty. It just indicates to the Object.clone() method that it is legal for that method to make a field-for-field copy of instances of that class (ref. docs.oracle.com/javase/7/docs/api/...). And because remote control should be only be were of Command interface, which doesn't have a copy-method, you still have the problem orginal problem how do you create a copy of an object which implements Command interface without doing something nasty. My solution would be that the Command interface would look something like this:

void execute();
void undo();
<T extends Command> T createCopy();

Now the remote control can create easily copies.

But yeah I think this is enough chit chat about this topic :)