问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/1940425/how-can-i-dynamically-look-up-a-static-class-member-in-clojure