问题描述
如何从Clojure获取Java类的方法?
strong>
下面的Per M Smith的注释完成了同样的操作,但提供了按方法名称排序,只返回方法:
(print-table
(sort-by:name
(filter:exception-types(:members(r / reflectfoo)))) )
[/ EDIT 2]
我的原始答案是指Clojure 1.2,这个工作没有依赖于Clojure的contrib库现在:
(require'[clojure.reflect:as r])
(使用'[clojure.pprint:only [print-table]])
(print-table(:members(r / reflectfoo)))
这提供了更多的解耦方法, reflect
函数提供了各种关于传递的参数的信息(在这种情况下, String
foo
)和 print-table
函数接受任何通用的表格数据结构,并且很好地打印它。
这本来是从。
[ / EDIT]
我将使用
中的 show
clojure.contrib.repl-utils
命名空间,它将打印对象(或对象的类)的所有静态和实例成员。我需要它像这样: (require'[clojure.contrib.repl-utils:as ru])
以下是使用Joda时间的示例:
(import'org.joda.time.DateTime)
(ru / show DateTime)
(ru / show(DateTime。))
第一个例子演示了如何简单地传递一个类到 show
你也可以传递一个类的实例。
这当然适用于许多Clojure项目是下面的Java类。下面是一个查看java.lang.String实例可用的所有方法的示例:
(ru / showfoo)
How can I get the methods of a Java class from Clojure?
[EDIT 2]
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]
[EDIT]
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")))
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.
This is originally from this thread on the Google Group.
[/EDIT]
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])
Here's an example using Joda Time:
(import 'org.joda.time.DateTime)
(ru/show DateTime)
(ru/show (DateTime.))
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.
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类的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!