与Java的toString()等效于Clojure函数 [英] Equivalent 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 >
在这里,WebDriver
代表一个类;您可以通过为相应的类实现print-method
来轻松地对内置Clojure数据结构执行此操作(Clojure的喜悦功能为clojure.lang.PersistentQueue
提供了print-method
,默认情况下没有漂亮的表示形式).上面的o
是您要处理的实际对象,而w
是编写器(这些打印功能需要).
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屋!