How to get the type of array elements in Clojure from fields declared in Java?

Following code

(-> (.getField (Class/forName
                "ccg.flow.processnodes.text.retrievers.Dictionary.Dictionary")
     "wordsTuples") .getType)

tells me what wordsTuplesis java.util.ArrayList. But I would like to know that it is an ArrayList with type elements String[], as it happens like this:

public class Dictionary extends ProcessNode {
    public ArrayList<String[]> wordsTuples;

    public ArrayList<String> words;
...

Is there a way to get type hint information programmatically within Clojure?

+4
source share
3 answers

Thanks to the comments, I found this answer on the question Get a generic type java.util.List . And from there, a simple modification of my sample code now works as desired:

(-> (.getField (Class/forName
             "ccg.flow.processnodes.text.retrievers.Dictionary.Dictionary")
     "wordsTuples") .getGenericType)

Return:

#<ParameterizedTypeImpl java.util.ArrayList<java.lang.String[]>>
0
source

You can use a simple hack based on the fact which data is on your list.

eg. you have a list of lines:

(def lst (java.util.ArrayList. ["my" "list" "of" "strings"]))

Then you can get the item type:

(if (and (instance? java.util.List lst) 
         (not (.isEmpty lst))) 
   (.getName (.getClass (.get lst 0))))

The disadvantage of this workaround is that you cannot get information about the empty b / c erase list mentioned by freakhill , but who cares about empty lists;)

Hope this helps.

0
source

All Articles