简体   繁体   中英

Is it possible to override .toString for a typed Java-Array in Clojure?

I have a Byte-Array like so:

(def byte-arr (byte-array (map byte "This is a test"))) ; => #<byte[] [B@63465272>

When calling .toString I get [B@1b96107b . Is it possible to override the .toString -Method of the clojure type [B to get This is a test instead, in that case?

It's a bad idea to globally assume all byte arrays are a printable strings, thus the advice to just use the String constructor is correct. That said, you can add new printing globally by type.

Printing functions eventually devolve to invocations of either print-method or print-dup multimethods, depending on whether *print-dup* is true. You can add a new method to print-method as follows using the print-sequential helper function in core_print.clj :

(in-ns 'clojure.core)

(def ^:private ByteArray (type (byte-array 0)))

(defmethod print-method ByteArray [ba ^Writer w]
  (print-sequential "[" pr-on " " "]" ba w))

Note this just prints a byte array as if it were a vector of bytes:

clojure.core=> (in-ns 'user)
#<Namespace user>
user=> (byte-array (map byte "This is a test"))
[84 104 105 115 32 105 115 32 97 32 116 101 115 116]

I don't recommend to override toString. It is too much global change and you might break some thing that relays on the default behaviour.

Why not creating a function for your specific requirement?

只需使用该字节数组构造一个String对象:

(println (String. byte-arr))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM