• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

clone an object

 
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

How do I clone an object in java without using clone method?

Thanks
 
Bartender
Posts: 2270
20
Android Java ME Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
http://weblogs.java.net/blog/emcmanus/archive/2007/04/cloning_java_ob.html
 
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Useful site, but it misses one thing out. It implies the return type of clone() is Object. Since Java5, it has been possible to use covariant return types, so you can have a clone() method in class Foo which returns a Foo reference.
The serialisation solution is a well‑known cheat, which does work, but only if the class implements Serializable. It also has slower performance.
Better solutions: If you want to copy your object, you can give the class a copy() method (rather like this, or a copy constructor, or a factory method which copies an object.
Better still, make your class immutable. Then you can forget all about cloning, copying, etc, because that will cease to be a problem.
reply
    Bookmark Topic Watch Topic
  • New Topic