This post originally started as a question, but I've since found a
solution. I thought I'd post it anyway, perhaps someone knows of a
nicer approach.

I'd like a function which maps from a boxed type as represented by a
java.lang.Class (i.e. Integer, Boolean, Float) to the associated
unboxed type. If no such unboxed doppelgänger exists, this function
should be identity.

This works:

(. java.lang.Integer TYPE)
=> int

Here's my attempt:

(defn unbox
  [class]
  (try (. class TYPE)
       (catch NoSuchFieldException e class)))

(unbox Integer)
; Evaluation aborted.
No matching field found: TYPE for class java.lang.Class
[Thrown class java.lang.IllegalArgumentException]

It's (naturally) trying to find TYPE in the class java.lang.Class,
which is the actual runtime type of the object that represents the
class Integer, as opposed to the class Integer itself.

This isn't Clojure's fault, it's just yet another consequence of Java
Classes not being objects in their own right. (Smalltalk, Objective-C,
Python, ... all do in one form or another.) No, the java.lang.Class,
which represents a class for purposes of reflection doesn't count.

With that insight, the following solution presents itself:

(defn unbox
  [class]
  (try (.. class (getField "TYPE") (get nil))
       (catch NoSuchFieldException e class)))

Thoughts?

// Ben

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to