简体   繁体   English

如何递归使用clojure.core / bean?

[英]How can I use clojure.core/bean recursively?

So I think clojure.core/bean is pretty close to what I want, but I'm working with a Java application that has nested beans, such that I end up with maps like this: 所以我认为clojure.core / bean非常接近我想要的,但是我正在使用一个嵌套bean的Java应用程序,这样我最终会得到这样的地图:

{:month-total 3835.0 :name "Jan's Meat Diner" :owners #<BarOwner[] [Lcom.fancypants.BarOwner;@1fb332d}

How, do I call bean recursively on a Java object so that I can get my imaginary BarOwner object to emit itself as a map, too: 如何,我在Java对象上递归调用bean ,以便我可以让我想象中的BarOwner对象自己作为地图发出:

{:month-total 3835.0 :name "Jan's Meat Diner" :owners { [:name "Jack"] [:name "Jill"] } }

Edit 1 编辑1

I have found that clojure/java.data and from-java is probably a better fit for this kind of thing than bean . 我发现clojure/java.datafrom-java可能比bean更适合这种事情。

Although it's probably not an ideal answer to "how to use bean recursively", using more of the richer contrib libraries under the Clojure community's site did solve it. 虽然它可能不是“如何递归使用bean”的理想答案,但在Clojure社区的网站下使用更多更丰富的contrib库确实解决了它。 Specifically 特别

clojure/java.data Clojure的/ java.data

provides simple recursive bean resolving, and can be configured to handle java types specifically in the hairy cases. 提供简单的递归bean解析,并且可以配置为在毛茸茸的情况下专门处理java类型。 I'd recommend this to other people who want to use bean . 我向其他想要使用bean人推荐这个。

It is very tricky to find out what is a bean and what is not. 找出什么是豆而不是什么是非常棘手的。 This seems to do the trick for beans inside beans and properties that are lists. 这似乎可以解决bean中的bean和列表属性的问题。 Probably you will want to add more classes to the probably-bean? 可能你会想要更多的类添加到probably-bean? function and perhaps some support for properties that are maps. 功能,也许是对地图属性的一些支持。

(defn probably-bean? [o]
   (and (not (coll? o))
         ((complement #{Class Long String clojure.lang.Keyword}) (class o))))

(defn transf [o]
    (cond
            (instance? java.util.List o) (into [] (map transf o))
            (probably-bean? o) (into {} (seq (bean o)))
            :else o))

(defn to-bean [o]
    (clojure.walk/prewalk #(transf %) o))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM