Welcome! Please see the About page for a little more info on how this works.

0 votes
ago in Clojure by

Consider the following function:

(defn clone [x] 
  (try (.clone x) 
  (catch CloneNotSupportedException _ ...)))

If the arg implements Cloneable, it works, but the call is reflective. If it doesn't, then it fails with java.lang.IllegalArgumentException: No matching field clone for class ....

I can get it to work by catching Exception instead, but it feels wrong :(

Any suggestions?

ago by
What exactly do you want to achieve?
ago by
Ultimately, I'd like the call to not be reflective - like in Java. Catching `Exception` feels like a hack, but it does work reliably so I am less bothered by it.

1 Answer

0 votes
ago by

clone() is a protected method - you should generally not call it on an arbitrary object. In Java, you can't even make that call, you'll get "clone() has protected access in java.lang.Object". It's a quirk of Clojure's impl that it even makes it possible via reflection.

So, my suggestion is to not call clone() at all. There are many, many reasons clone() is problematic and considered one of the more questionable features of Java's early design.

...