无法访问Clojure中的静态方法

时间:2018-06-17 14:39:07

标签: clojure

尝试访问某个类的静态方法时遇到问题。 这是代码和错误消息:

(ns demo.app
  (:import 
     [java.nio.file Paths]
     [java.util List])

=> (Paths/get "a" "B" "c")
CompilerException java.lang.IllegalArgumentException: No matching method: get, compiling:(*cider-repl clj-demo*:68:16) 

=> (java.nio.file.Paths/get ".")
ClassCastException java.lang.String cannot be cast to java.net.URI  clj-demo.ch08/eval11327 (form-init3786136217280477578.clj:76)

=> (java.nio.file.Paths/get "." "finally.txt")
ClassCastException java.lang.String cannot be cast to [Ljava.lang.String;  clj-demo.ch08/eval11329 (form-init3786136217280477578.clj:78)

java doc如下: https://docs.oracle.com/javase/10/docs/api/java/nio/file/Paths.html#get(java.lang.String,java.lang.String...)

我在https://clojure.org/reference/java_interop找到了它,它写道:

  

(Classname / staticMethod args *)

我也试过这些:

=> (System/getProperty "java.vm.version")
"25.102-b14"

=> (clojure-version)
"1.8.0"

没问题。所以:

为什么Paths/get在REPL中不起作用?

为什么java.nio.file.Paths/get不起作用?

为什么Paths/getjava.nio.file.Paths/get会收到不同的错误消息?

我也试过

(List/of 0) ;; => [0]
(List/of 1 2 3) ;; => Method
   java.util.List.of(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)Ljava/util/List;
   must be InterfaceMethodref constant
(List/of (Integer. 1)) ;; =>  Method java.util.List.of(Ljava/lang/Object;)Ljava/util/List; must
   be InterfaceMethodref constant
(List/of "s") ;; =>    Method java.util.List.of(Ljava/lang/Object;)Ljava/util/List; must
   be InterfaceMethodref constant

1 个答案:

答案 0 :(得分:4)

Paths.get(String, String...)有两个参数 - 一个字符串和一个字符串数组。 Java会自动为您创建数组,但在clojure中,您需要自己构建数组,例如

(Paths/get "a" (into-array String ["b" "c"]))

调用

(java.nio.file.Paths/get ".")

失败,因为唯一需要一个参数的overload of get要求它是URI而不是String