Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I dynamically look up a static class member in Clojure?

Tags:

java

clojure

In Clojure I can look up a static member of a Java class (e.g. a field holding a constant) like this:

ClassName/CONSTANT_FIELD

How can I access the member when I only know it's name at runtime? An example would be looping over a sequence of field names and getting all the field values.

I would like to do something like this (this code is not working, of course):

(let [c "CONSTANT_FIELD"]
  ClassName/c)

What's the best way to do that?

like image 659
Christian Berg Avatar asked Dec 21 '09 14:12

Christian Berg


1 Answers

You can use Java's reflection API.

(let [c "CONSTANT_FIELD"]
  (.get (.getField ClassName c) nil))

The nil is there because you are getting a static field, rather than a member field of a particular object.

like image 161
djpowell Avatar answered Nov 16 '22 08:11

djpowell