I came across following statements from java official docs:
In
Cloneable[ref]
- A class implements the Cloneable interface to indicate to the
Object.clone()method that it is legal for that method to make a field-for-field copy of instances of that class.- Invoking Object's clone method on an instance that does not implement the
Cloneableinterface results in the exceptionCloneNotSupportedExceptionbeing thrown.- Note that this interface does not contain the
clonemethod. Therefore, it is not possible to clone an object merely by virtue of the fact that it implements this interface.
So, I was guessing how Object might be checking whether the instance implements Cloneable or not and throwing CloneNotSupportedException. So, I checked the implementation of clone() in java source, and it contains native declaration:
protected native Object clone() throws CloneNotSupportedException;
When I checked java_lang_Object.c for native implementation, I found this:
JNIEXPORT jobject JNICALL Java_java_lang_Object_clone
(JNIEnv *env, jobject obj) {
struct claz *claz = FNI_CLAZ(FNI_UNWRAP_MASKED(obj));
uint32_t size = claz->size;
assert(claz->component_claz==NULL/* not an array*/);
return fni_object_cloneHelper(env, obj, size);
}
So, I am not finding what makes Object.clone() to throw CloneNotSupportedException if the instance does not implement Cloneable. To be precise, which line of code throws CloneNotSupportedException? I am missing something stupid?