Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a type symbol to a java.lang.Class instance

Tags:

clojure

Here is my problem: Suppose I require clojure.reflect :as r and then, for example, do

(->> (r/reflect java.lang.String)
                :members
                (filter #(= (:name %) 'getBytes))
                first
                :return-type)

This will evaluate to byte<> which is a symbol. How can I map that symbol to a Java class, that is, how can I write a function type-symbol-to-class such that

(assert
  (= (class (byte-array [1 2 3]))
     (type-symbol-to-class 'byte<>))) 

does not throw an exception? It is good if that function works for more symbols than just byte<>.

like image 947
Rulle Avatar asked Jan 28 '23 00:01

Rulle


1 Answers

Clojure reflection library does a lot of work (1, 2, 3) to prettify the output (including the argument / return type names) and it is not a straightforward task to do a reverse transform.

If you need a Class object, you can just use Java's reflection tools instead of clojure.reflect:

(= (->> java.lang.String
        .getDeclaredMethods
        (filter #(= (.getName %) "getBytes"))
        first
        .getReturnType)
   (class (byte-array [1 2 3]))) # -> true
like image 91
Aleph Aleph Avatar answered Jan 30 '23 15:01

Aleph Aleph