Problems calling a Java function variable from Clojure

I have a game with the Java NIO.2 API from JDK 7.

In particular, I want to call the method: Paths#get(String first, String... more)

This is a static method that takes at least one row and returns its corresponding Path object. There's an overloaded form: Paths#get(URI uri)

However, I cannot name the top method from Clojure. The closest I can get is this:

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

which fails:

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

as you might expect. In the end, we pass the object [] to what String [] expects.

I tried to remove the form (object-array), but it just makes Clojure try to call the get (URI) method - with or without a type hint.

Passing nil as the second argument to Paths # get (String, String ...) calls the correct method, which is called, but Java 7 then does not work with NPE.

I cannot find a way in Clojure to express the type String [] - I assume that I need to either do this or give a hint to the sending system.

Any ideas?

+6
source share
1 answer

As you noticed, he does not want Object [], he wants String []. object-array does exactly what it says: it creates an array of objects. If you want to create an array with a different type, make-array and into-array are your friends. For example here:

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

The String is optional in this case: if you do not specify the desired array type, Clojure uses the type of the first object as the type of the array element.

+16
source

Source: https://habr.com/ru/post/885743/


All Articles