Search code examples
javainterfaceclone

Java: Making a copy of an object when you only have access to an interface


I am using an API that gives access to a certain set of subclasses with a common interface. I use the interface throughout my code, and the instances are resolved to the proper subclass based on user needs. My problem is that I need to create a copy of one of these objects, but I don't have access to the clone() method and the API doesn't provide a copy constructor. ie:

ObjectInterface myObject = objectFromParameter.clone(); //Not possible...

Is there a workaround in Java?


Solution

  • iYou might be able to do what you want with reflection. Alternatively, If the object supports serialization, you can serialize to a byte array and then reconstruct a new instance from that.