如何在Clojure中查看与对象关联的方法?

时间:2011-11-02 19:22:12

标签: java methods clojure

我在Clojure中使用什么函数来查看Java对象的方法?

user=> (some-function some-java-object)
... lots of methods ...

6 个答案:

答案 0 :(得分:10)

使用java反射。

(.getClass myObject)

让你上课。要获得方法,

(.getMethods (.getClass myObject))

它为您提供了一系列方法。你可以把它当成一个序列;我可能把它放到一个矢量中,所以:

(vec (.getMethods (.getClass myObject)))

答案 1 :(得分:9)

从版本1.3开始,Clojure与clojure.reflect命名空间捆绑在一起。特别是函数reflect可用于显示对象的所有方法(和其他信息)。使用show并不方便。另一方面,它更通用,使用show作为构建块编写自己的reflect版本非常容易。

例如,如果要查看返回String的所有String方法:

user=> (use 'clojure.reflect)
user=> (use 'clojure.pprint)

user=> (->> (reflect "some object") 
            :members 
            (filter #(= (:return-type %) 'java.lang.String))
            (map #(select-keys % [:name :parameter-types])) 
            print-table)

答案 2 :(得分:5)

user=> (map #(.getName %) (-> "foo" class .getMethods))

("equals" "toString" "hashCode" "compareTo" "compareTo" "indexOf" "indexOf" "indexOf" "indexOf" "valueOf" "valueOf" "valueOf" "valueOf" "valueOf" "valueOf" "valueOf" "valueOf" "valueOf" "length" "isEmpty" "charAt" "codePointAt" "codePointBefore" "codePointCount" "offsetByCodePoints" "getChars" "getBytes" "getBytes" "getBytes" "getBytes" "contentEquals" "contentEquals" "equalsIgnoreCase" "compareToIgnoreCase" "regionMatches" "regionMatches" "startsWith" "startsWith" "endsWith" "lastIndexOf" "lastIndexOf" "lastIndexOf" "lastIndexOf" "substring" "substring" "subSequence" "concat" "replace" "replace" "matches" "contains" "replaceFirst" "replaceAll" "split" "split" "toLowerCase" "toLowerCase" "toUpperCase" "toUpperCase" "trim" "toCharArray" "format" "format" "copyValueOf" "copyValueOf" "intern" "wait" "wait" "wait" "getClass" "notify" "notifyAll")

将“foo”替换为您的对象。

答案 3 :(得分:2)

您以前可以使用show进行此类操作(例如,使用clojure 1.2.0,clojure-contrib 1.2.0)。

(ns test.core
  (:use [ clojure.contrib.repl-utils :only [show]]))

来自REPL

(show Integer)

产生

===  public final java.lang.Integer  ===
static MAX_VALUE : int 
static MIN_VALUE : int
... 

奇怪的是,我尝试使用clojure 1.3.0 / clojure-contrib 1.2.0并且它没有用。 doc似乎也被打破了。

答案 4 :(得分:1)

IIRC它不是内置的,但它也很短 - see this implementation

(现在可能是。)

答案 5 :(得分:1)

您通常会使用此方法列表,因为您正在寻找特定类型的方法。所有" get"班里的那种方法。您可以通过以下方式为对象' obj'

执行此操作
(filter #(re-find #"get" %) (map #(.getName %) (.. obj getClass getMethods)))

#" get"是正则表达式对象,用于搜索名称中包含get的方法(根据自己的需要自定义)。 map表达式只是生成对象类中所有方法名称的seq; seq被送到匿名函数,该函数是传递给过滤器的第一个参数。