The Object.clone() method in Java is pretty special, as instead of returning a copy of the object that is to be cloned with the Object type, it returns the correct Object type. This can be better described with the following code:
class A implements Cloneable
{
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
class B extends A {
}
public class MainABC {
public static void main(String[] args) throws CloneNotSupportedException {
B b = new B();
B b1 = (B)b.clone(); //see here that we are using A's .clone(). The only
//thing it does is call Object's clone().
System.out.println(b1.getClass()); //but as we see here, its not an Object
//its a B!
}
}
So, could anyone explain if possible if is there anyway to replicate what happens inside Object.clone()’s method?
It is definitely true that
Object.clone()does a few things that simply can not be achieved in Java.From Josh Bloch on Design: Copy Constructor versus Cloning (emphasis mine):
Object.clone()does something that isn’t supposed to be allowed by the language. That is why, among many other reasons,clone()is broken.(If you haven’t already, you should also read his book Effective Java, to understand why he (and many others) think that Java’s
clone()andCloneableis broken).If you just want to create an object of the same class as another arbitrary object, then this is actually quite achievable, with some caveat (namely that not all types are publicly instantiable) by using reflection.
Here’s an example of how to use reflection to:
parameter.
Output:
Note that this is just an example to show type can be inspected at run time and a copy constructor can be looked for and invoked. As is, it doesn’t work if
ois anArrayList, because it has no constructor that takes anArrayList(it does have one that takes aCollection, which anArrayListis).I’ll leave it to you as an exercise on how to expand the search for the copy constructor to include these compatible overloads.