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

 ̄綄美尐妖づ 提交于 2019-12-22 04:33:15

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!