如何在Clojure中动态查找静态类成员? [英] How can I dynamically look up a static class member in Clojure?

查看:189
本文介绍了如何在Clojure中动态查找静态类成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Clojure中,我可以查找一个Java类的静态成员(例如,一个字段包含一个常量),如下所示:

  ClassName / CONSTANT_FIELD 



当我在运行时只知道它的名称时,如何访问成员?一个例子是循环一系列字段名并获取所有的字段值。



我想这样做(这个代码不工作,当然):

 (let [cCONSTANT_FIELD] 
ClassName / c)



最好的方法是什么?

解决方案

您可以使用Java的反射API。

 (let [cCONSTANT_FIELD] 
(.getField ClassName c)nil))

nil是因为你得到一个静态字段,而不是特定对象的成员字段。


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?

解决方案

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.

这篇关于如何在Clojure中动态查找静态类成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆