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

Mat*_*ick 11 java methods clojure

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

user=> (some-function some-java-object)
... lots of methods ...
Run Code Online (Sandbox Code Playgroud)

Rob*_*lan 10

使用java反射.

(.getClass myObject)
Run Code Online (Sandbox Code Playgroud)

让你上课.要获得方法,

(.getMethods (.getClass myObject))
Run Code Online (Sandbox Code Playgroud)

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

(vec (.getMethods (.getClass myObject)))
Run Code Online (Sandbox Code Playgroud)


Jon*_*nas 10

从版本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)
Run Code Online (Sandbox Code Playgroud)


Bil*_*ill 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")
Run Code Online (Sandbox Code Playgroud)

用您的对象替换“ foo”。