Java的toString()对Clojure函数的等式 [英] Equivilent of Java's toString() for Clojure functions
问题描述
一些Java代码我使用在我的Clojure函数对象上调用 toString()
,它返回类似#< ns $ something something .something $ something @ 7ce1eae7>>
- 我想返回别的东西...可能有一种方法来在函数中包含一些元数据,所以他们的对象的 toString()
some Java code I'm using invokes toString()
on my Clojure function objects, which return something like #<ns$something something.something$something@7ce1eae7>>
- I want to return something else...presumably there's a way to include some metadata in the functions so their objects' toString()
returns that instead ?
推荐答案
如果你只想打印出对象的REPL更有意义的是,您可以为有问题的类实现 defmethod print-method
。
If you just want to make the REPL print-out of your objects more meaningful, you can implement a defmethod print-method
for the class in question.
我最近写的一些代码;这使得Selenium-WebDriver WebDriver对象的REPL打印更有意义:
Here's a shortened version of some code I've written recently; this makes the REPL print-out of a Selenium-WebDriver WebDriver object more meaningful:
(defmethod print-method WebDriver
[o w]
(print-simple
(str "#<" "Title: " (.getTitle o) ", "
"URL: " (.getCurrentUrl o) " >")
w))
; Title:A Title,URL: http://example.com >
This prints out like #<Title: A Title, URL: http://example.com >
这里, WebDriver
代表一个类;你可以通过为适当的类实现 print-method
,为内置的Clojure数据结构轻松做到这一点(The Joy of Clojure features a print -method
for clojure.lang.PersistentQueue
,它在默认情况下没有很好的表示)。上面的 o
是你正在处理的实际对象, w
是一个writer函数)。
Here, WebDriver
represents a class; you can just as easily do this for built-in Clojure data structures by implementing print-method
for the appropriate class (The Joy of Clojure features a print-method
for clojure.lang.PersistentQueue
which has no nice representation by default). The o
above is the actual object you're dealing with and w
is a writer (required by these kinds of print functions).
这篇关于Java的toString()对Clojure函数的等式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!