0

How can I, and What is the best/proper way (ie, most performant and clearest syntactically) in Java to create object instances based on a prototype object instance, when this will occur repeatedly and in a performance critical code path?

I have thought about cloning via a cloning support library, but is that the best/only way? (These need to be arbitrary objects, btw, not ones that implement Clonable).

To clarify what I mean: I have an existing instance of Class T, which has fields set on it, and I want to pop out many versions of the same object to use separately, with the best performance and syntactic clarity possible.

Thanks.

mtyson
  • 8,196
  • 16
  • 66
  • 106

1 Answers1

1

Create a builder, which receives this class instance:

Person newOne = new PersonBuidler(oldOne).setAge(42)

Implementation of this builder may use apache common BeanUtils for cloning Java Beans or some other utility library for cloning arbitrary class. See How do I copy an object in Java?

Community
  • 1
  • 1
Pavel Bernshtam
  • 4,232
  • 8
  • 38
  • 62