0

Possible Duplicate:
How to properly override clone method?

I have a simple class that has a bunch of primitive variables in it, about 100-200 total. It's structured very simply, like this:

public class Level implements Clonable {
    int speed; 
    boolean wallKicks;
    boolean bigMode;
    float targetFrequency;
    long milliseconds;
    double fade;
    int[] perfectPenalties;
    <100 or so more things like this>
}

I need to be able to clone this class. Right now, I've just explicitly typed out the copy action for each member variable in my clone() method:

public Object clone() {
     Level newLevel = new Level();
     newLevel.speed = speed;
     newLevel.wallKicks = wallKicks;
     newLevel.bigMode = bigMode;
     newLevel.perfectPenalties = perfectPenalties.clone();
     <etc>
}

The problem is that it's a bit of a task to be sure that I haven't missed any values in my clone method. In the future I'd also like to implement an equals() function, which would mean I'd have to manually synchronize the data in 3 places. Not pleasant.

Is there any easier way to accomplish this? I'm open to programatic solutions or anything else that does the job. I'd just like to have something easier than looking at the three side-by-side and matching variable for variable.

Thank you.

Community
  • 1
  • 1
Grumblesaurus
  • 3,021
  • 3
  • 31
  • 61

1 Answers1

2

yes, you can use following approaches to cloning:

1) Java Serialization mechanism to clone your object:

ByteArrayOutputStream bout = new ByteArrayOutputStream();
out = new ObjectOutputStream(bout);

out.writeObject(obj);
out.close();

ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
in = new ObjectInputStream(bin);            
Object copy = in.readObject();

2) apache.commons.lang library has a org.apache.commons.lang.SerializationUtils.clone()

3) use dozer library

4) user Kyro, although I've never used it

for equals() use org.apache.commons.lang.builder.EqualsBuilder.reflectionEquals()

mantrid
  • 2,830
  • 21
  • 18
  • Does the serialization method have any speed issues? If not, that seems like a perfect solution. – Grumblesaurus Feb 03 '13 at 02:40
  • serialization should be far faster than dozer or Kyro as it doesn't use reflection. – mantrid Feb 03 '13 at 02:44
  • How do you imagine it's speed would be as compared to the handwritten method I've described above? As long as there's not a major speed issue, then this solution is the solution I'm looking for. The class doesn't get cloned too much. 10-25 times whenever a new levelsystem is loaded. So as long as there aren't glaring speed problems, this sounds like the trick. – Grumblesaurus Feb 03 '13 at 02:46