0

Consider the code below:

Project project1 = new Project("string1","string2","string3","string4","string5", ...);
Project project2 = project1;

Here, project2 is not a copy of project1, because it points to the same object. It significate that if I edit project2, it also edit project1.

I want project2 to be independent of project1. I suppose that I can make a constructor with a Project param like:

public Project(Project project) {
    this.string1 = project.getString1();
    this.string2 = project.getString2();
    ...
}

I my case, I have something like 15 attributes in my Project class, so doing this would require me to write a big constructor.

Is there a better way to do this ? :)

Thanks !

Mistalis
  • 17,793
  • 13
  • 73
  • 97

1 Answers1

2

No, there is not a better way to do that. You could use clone, but... don't. Don't use clone.

Community
  • 1
  • 1
Sam Estep
  • 12,974
  • 2
  • 37
  • 75
  • Really ? :/ With smart classes it is quiet good, but with big classes, it could be very long ... – Mistalis Jul 08 '15 at 12:58
  • 1
    @Mistalis Yes, that's correct. That's one reason why you shouldn't create gigantic classes. – Sam Estep Jul 08 '15 at 12:59
  • I know big classes is a bad idea, but in my case, I didn't find a way to do something better :-D I will make a constructor by copy so ... – Mistalis Jul 08 '15 at 13:04
  • @Mistalis http://stackoverflow.com/a/3333989/1080648 may be relevant to avoid the manual copying of attributes, although read the linked articles carefully to make sure it's right for your setup – Jon Story Jun 29 '16 at 14:29
  • @JonStory Using reflection for this is going to be very, very slow. I would say that, any time you have a class so big that you're considering using reflection to loop through its attributes when copying it, that's a sign that you have some refactoring to do. – Sam Estep Jun 29 '16 at 14:50