Helper functions for accessing properties in clojure-clr 1.2.0

103 views
Skip to first unread message

Matthew D. Swank

unread,
Feb 1, 2011, 7:10:57 PM2/1/11
to Clojure
AFAIK clojure-clr doesn't have built-in support for accessing
properties. Something like this has probably been posted before, but
I've been playing with Windows.Forms, and I found the following
useful.

(import '(System Type Array Exception)
'(System.Reflection PropertyInfo MethodInfo))
(defn prop-get [object prop-name]
(let [prop-name
(if (symbol? prop-name)
(name prop-name)
prop-name)
o-type (type object)
prop (when o-type (.GetProperty o-type prop-name))
getter (when prop (.GetGetMethod prop))]
(when getter
(.Invoke getter object nil))))

(defn prop-set! [object prop-name value]
(let [prop-name
(if (symbol? prop-name)
(name prop-name)
prop-name)
o-type (type object)
v-type (type value)
prop (when o-type (.GetProperty o-type prop-name))
setter (when prop (.GetSetMethod prop))
arg (when v-type (Array/CreateInstance v-type 1))]
(when (and setter arg)
(.SetValue arg value 0)
(.Invoke setter object arg))))

;;e.g
(let [e (Exception.)]
(prop-set! e 'HelpLink "file:///foo.txt")
(prop-get e 'HelpLink))
=> "file:///foo.txt"

Matthew D. Swank

unread,
Feb 2, 2011, 10:09:37 PM2/2/11
to Clojure
On Feb 1, 6:10 pm, "Matthew D. Swank" <akopa.gmane.pos...@gmail.com>
wrote:
> AFAIK clojure-clr doesn't have built-in support for accessing
> properties.  

Ok David Miller let me know off list the existing interop handle
properties.

dmiller

unread,
Feb 2, 2011, 10:44:24 PM2/2/11
to Clojure
Specifically, in ClojureCLR< property access in CLR interop is treated
in the same way as fields and zero-arity methods.

For class properties, ClassName/PropertyName works.
For instance properties, (.PropertyName instance) or (. instance
PropertyName)

In essence, fields, properties and zero-arity methods are referenced
in the same way, and are checked in this order.
You can also access the getter/setter methods of a property directly.
(get_PropertyName and (set_PropertyName)

Where properties are not handled is in type/interface specification/
implementation. Specifically, places that allow method definition
(gen-interface and company) and places that allow method definition
(deftype and company) do not allow specification of properties.
Technically, this is quite easy. The difficutly is that the syntax of
these macros typically do not make it easy to distinguish the intent
of defining properties versus defining zero-arity methods. This is
discussed more fully at https://github.com/richhickey/clojure-clr/wiki/Extending-deftype-and-company-for-CLR.

I still need to come up with a good mechanism for referring to
events. Suggestions welcomed.

--David


On Feb 2, 9:09 pm, "Matthew D. Swank" <akopa.gmane.pos...@gmail.com>
Reply all
Reply to author
Forward
0 new messages