如何从 Clojure 获取 Java 类的方法? [英] How can I get the methods of a Java class from Clojure?
问题描述
如何从 Clojure 获取 Java 类的方法?
How can I get the methods of a Java class from Clojure?
推荐答案
根据下面 M Smith 的评论,这实现了相同的功能,但提供按方法名称排序且仅返回方法:
Per M Smith's comment below, this accomplishes the same but provides sorting by method name and only returns methods:
(print-table
(sort-by :name
(filter :exception-types (:members (r/reflect "foo")))))
[/EDIT 2]
我最初的回答是指 Clojure 1.2,但随着 Clojure 1.3 的出现,情况发生了变化.现在无需依赖 Clojure 的 contrib 库即可工作:
My original answer refers to Clojure 1.2, but things have changed with Clojure 1.3. This works without any reliance on Clojure's contrib libraries now:
(require '[clojure.reflect :as r])
(use '[clojure.pprint :only [print-table]])
(print-table (:members (r/reflect "foo")))
这提供了一种更加解耦的方法,reflect
函数提供有关传入参数的各种信息(在这种情况下,一个 String
"foo"
) 和 print-table
函数采用任何通用表格数据结构并漂亮地打印出来.
This provides a much more decoupled approach, with the reflect
function providing all kinds of information on the argument passed in (in this case, a String
"foo"
) and the print-table
function taking any generic tabular data structure and pretty printing it as such.
这最初来自Google 网上论坛上的这个帖子.
[/EDIT]
我会在 clojure.contrib.repl-utils
命名空间中使用 show
函数,它将打印一个对象(或类一个东西).我这样要求:
I'd use the show
function in the clojure.contrib.repl-utils
namespace, which will print all static and instance members for an object (or class of an object). I require it like so:
(require '[clojure.contrib.repl-utils :as ru])
以下是使用 Joda Time 的示例:
Here's an example using Joda Time:
(import 'org.joda.time.DateTime)
(ru/show DateTime)
(ru/show (DateTime.))
第一个示例演示了如何简单地将类传递给 show
,而第二个示例演示了您也可以传递类的实例.
The first example demonstrates how you can simply pass a class to show
, while the second demonstrates that you can pass an instance of the class as well.
这当然适用于许多底层 Java 类的 Clojure 项目.这是查看 java.lang.String 实例可用的所有方法的示例:
This of course works for lots of Clojure items that are Java classes underneath. Here's an example of seeing all methods available to an instance of java.lang.String:
(ru/show "foo")
这篇关于如何从 Clojure 获取 Java 类的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!