2

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 Cloneable interface results in the exception CloneNotSupportedException being thrown.
  • Note that this interface does not contain the clone method. 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?

MsA
  • 2,599
  • 3
  • 22
  • 47
  • You can't call the method you're pointed, as it's protected. You may override the method in your class – azro Mar 18 '20 at 16:16
  • Yes but we dont have to throw the exception ourselves if the class does not implement `Cloneable`. So what (from where) does the exception is thrown? – MsA Mar 18 '20 at 16:18
  • Yes it seems. [Line 566](https://github.com/openjdk-mirror/jdk7u-hotspot/blob/50bdefc3afe944ca74c3093e7448d6b889cd20d1/src/share/vm/prims/jvm.cpp#L566) is responsible for throwing `CloneNotSupportedException`, right? – MsA Mar 18 '20 at 18:13

0 Answers0