【问题标题】:In Clojure how do I get the basis for a record with only an instance of the record?在 Clojure 中,我如何获得只有记录实例的记录的基础?
【发布时间】:2013-02-28 06:28:15
【问题描述】:

我在 Clojure 中有一个记录

(defrecord Animal [name age])

我可以轻松创建记录的实例

(def my-cat (Animal. "spot" 2))

我也可以用map->Animal函数创建一个实例

(def my-dog (map->Animal {:name "snowy" :age 6 :legs 3}))

创造

#user.Animal{:name "snowy", :age 6, :legs 3}

仅给定Animal 的一个实例,例如my-dog,我如何获得基础?

我知道我可以在Animal 上进行静态调用以获取它,如下所示:

(Animal/getBasis)

这给出了[name age],但我如何从my-dog 得到这个?

【问题讨论】:

    标签: clojure record


    【解决方案1】:

    问题似乎在于 clojure 对静态方法调用的处理。这是一些可以得到答案的代码

    user=> (defrecord Animal [name age])
    user.Animal
    user=> (def my-dog (map->Animal {:name "snowy" :age 6 :legs 3}))
    #'user/my-dog
    user=> (. (. (type my-dog) getMethod "getBasis" nil) invoke nil nil)
    [name age]
    

    这个in another SO thread有更长的讨论

    【讨论】:

    • 谢谢。这很有帮助。我认为底线比(.. (type my-dog) (getMethod "getBasis" nil) (invoke nil nil)) 更漂亮,但感觉是相同的。
    猜你喜欢
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-18
    • 2012-07-29
    • 2015-01-29
    相关资源
    最近更新 更多