简体   繁体   English

从Clojure调用可变参数Java函数的问题

[英]Problems calling a variadic Java function from Clojure

I'm having a play with the Java NIO.2 API from JDK 7. 我正在玩JDK 7的Java NIO.2 API。

In particular, I want to call the method: Paths#get(String first, String... more) 特别是,我想调用方法: Paths#get(String first, String... more)

This is a static method which takes in at least one string, and returns a Path object corresponding to it. 这是一个静态方法,它至少接收一个字符串,并返回与之对应的Path对象。 There's an overloaded form: Paths#get(URI uri) 有一个重载的形式: Paths#get(URI uri)

However, I can't seem to call the top method from Clojure. 但是,我似乎无法从Clojure中调用top方法。 The nearest I can seem to get is this: 我最近能得到的是:

(Paths/get ^String dir-fq (object-array 0))

which fails with: 失败的是:

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;

as you might expect. 正如你所料。 After all, we're passing in an Object[] to something that's expecting String[]. 毕竟,我们将Object []传递给期望String []的东西。

I've tried removing the (object-array) form - but that just causes Clojure to try to call the get(URI) method - both with and without the type hint. 我已经尝试删除(对象数组)表单 - 但这只会导致Clojure尝试调用get(URI)方法 - 无论是否有类型提示。

Passing nil as the second argument to Paths#get(String, String...) causes the right method to be called, but Java 7 then fails with an NPE. 将nil作为Paths#get(String,String ...)的第二个参数传递会导致调用正确的方法,但Java 7随后会因NPE而失败。

I can't seem to find a way in Clojure to express the type String[] - I'm guessing I either need to do that or provide a hint to the dispatch system. 我似乎无法在Clojure中找到表达String []类型的方法 - 我猜我需要这样做或者为调度系统提供一个提示。

Any ideas? 有任何想法吗?

As you noticed, it doesn't want an Object[], it wants a String[]. 正如您所注意到的,它不需要Object [],它需要String []。 object-array does exactly what it says: it makes an array of objects. object-array正如它所说的那样:它创建一个对象数组。 If you want to create an array with some different type, make-array and into-array are your friends. 如果你想创建一个具有不同类型make-arraymake-arrayinto-array是你的朋友。 For example here: 例如这里:

(Paths/get "foo" (into-array String ["bar" "baz"]))

The String specifier there is optional in this case: if you leave out the array's desired type, Clojure uses the type of the first object as the array's component type. 在这种情况下, String说明符是可选的:如果省略数组的所需类型,Clojure使用第一个对象的类型作为数组的组件类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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