Clojure에서 Java 클래스의 메소드를 얻으려면 어떻게해야합니까?
Clojure에서 Java 클래스의 메소드를 얻으려면 어떻게해야합니까?
[편집 2]
아래의 M Smith의 설명에 따라 이것은 동일한 작업을 수행하지만 메서드 이름별로 정렬을 제공하고 메서드 만 반환합니다.
(print-table
(sort-by :name
(filter :exception-types (:members (r/reflect "foo")))))
[/ 편집 2]
[편집하다]
내 원래 대답은 Clojure 1.2를 참조했지만 Clojure 1.3에서는 상황이 변경되었습니다. 이것은 Clojure의 contrib 라이브러리에 의존하지 않고 작동합니다.
(require '[clojure.reflect :as r])
(use '[clojure.pprint :only [print-table]])
(print-table (:members (r/reflect "foo")))
이것은 reflect
전달 된 인수 (이 경우 a String
"foo"
) 에 대한 모든 종류의 정보를 제공 하는 print-table
함수 와 일반적인 테이블 형식 데이터 구조를 취하고 그와 같이 예쁜 인쇄 를하는 함수 와 함께 훨씬 더 분리 된 접근 방식을 제공합니다 .
이것은 원래 Google 그룹의이 스레드에서 가져온 것 입니다.
[/편집하다]
개체 (또는 개체의 클래스)에 대한 모든 정적 및 인스턴스 멤버를 인쇄 show
하는 clojure.contrib.repl-utils
네임 스페이스 의 함수를 사용합니다 . 다음과 같이 필요합니다.
(require '[clojure.contrib.repl-utils :as ru])
다음은 Joda Time을 사용한 예입니다.
(import 'org.joda.time.DateTime)
(ru/show DateTime)
(ru/show (DateTime.))
첫 번째 예제는 단순히 클래스를에 전달하는 방법을 보여주고 두 번째 예제는 클래스 show
의 인스턴스도 전달할 수 있음을 보여줍니다.
물론 이것은 Java 클래스 아래에있는 많은 Clojure 항목에서 작동합니다. 다음은 java.lang.String의 인스턴스에 사용할 수있는 모든 메소드를 보는 예입니다.
(ru/show "foo")
최근 Clojure 1.3.0-alpha * 릴리스에서 사용할 수있는 clojure.reflect를 사용해보십시오 . 필요에 따라 검색 / 필터링 할 수있는 Clojure 데이터 구조를 반환합니다.
Clojure 1.3.0-alpha6
user=> (use 'clojure.reflect 'clojure.pprint)
nil
user=> (pprint (reflect "hello"))
{:bases
#{java.io.Serializable java.lang.Comparable java.lang.Object
java.lang.CharSequence},
:flags #{:public :final},
:members
#{{:name valueOf,
:return-type java.lang.String,
:declaring-class java.lang.String,
:parameter-types [boolean],
:exception-types [],
:flags #{:static :public}}
...
clojure.reflect를 사용하고 이전 답변을 확장하는이 방법을 사용할 수 있습니다.
(use 'clojure.reflect)
(defn all-methods [x]
(->> x reflect
:members
(filter :return-type)
(map :name)
sort
(map #(str "." %) )
distinct
println))
용법:
(all-methods "")
; => (.charAt .checkBounds .codePointAt .codePointBefore .codePointCount .compareTo .compareToIgnoreCase .concat .contains .contentEquals .copyValueOf .endsWith .equals .equalsIgnoreCase .format .getBytes .getChars .hashCode .indexOf .intern .isEmpty .lastIndexOf .length .matches .offsetByCodePoints .regionMatches .replace .replaceAll .replaceFirst .split .startsWith .subSequence .substring .toCharArray .toLowerCase .toString .toUpperCase .trim .valueOf)
(all-methods 1)
; => (.bitCount .byteValue .compareTo .decode .doubleValue .equals .floatValue .getChars .getLong .hashCode .highestOneBit .intValue .longValue .lowestOneBit .numberOfLeadingZeros .numberOfTrailingZeros .parseLong .reverse .reverseBytes .rotateLeft .rotateRight .shortValue .signum .stringSize .toBinaryString .toHexString .toOctalString .toString .toUnsignedString .valueOf)
(all-methods java.util.StringTokenizer)
; => (.countTokens .hasMoreElements .hasMoreTokens .isDelimiter .nextElement .nextToken .scanToken .setMaxDelimCodePoint .skipDelimiters)
This code will print all public methods, both declared and inherited.
(doseq [m (.getMethods (type "Hello"))]
(println "Method Name: " (.getName m))
(println "Return Type: " (.getReturnType m) "\n"))
this will return Java array of declared methods:
(:declaredMethods (bean String))
(seq (:declaredMethods (bean String)))
advantage is bean is in clojure.core
Try my new library:
http://github.com/zcaudate/iroh
(.? String #"^c" :name)
;;=> ["charAt" "checkBounds" "codePointAt" "codePointBefore"
;; "codePointCount" "compareTo" "compareToIgnoreCase".
;; "concat" "contains" "contentEquals" "copyValueOf"]
참고URL : https://stackoverflow.com/questions/5821286/how-can-i-get-the-methods-of-a-java-class-from-clojure
'Program Tip' 카테고리의 다른 글
Android는 내 인 텐트 Extras를 계속 캐싱합니다. 새로운 추가 항목을 유지하는 보류중인 인 텐트를 선언하는 방법은 무엇입니까? (0) | 2020.11.30 |
---|---|
Google App Engine으로 타사 Python 라이브러리를 관리하려면 어떻게하나요? (0) | 2020.11.30 |
Rails 3 및 Heroku : 푸시시 자동으로 "rake db : migrate"? (0) | 2020.11.30 |
Unix 찾기 : 여러 파일 유형 (0) | 2020.11.30 |
Rails : 3 개 열의 고유 한 조합 확인 (0) | 2020.11.30 |