如何在 Clojure 中从 Java 中声明的字段获取数组元素的类型?

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

代码如下

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

告诉我 wordsTuplesjava.util.ArrayList。但我想知道的是,它是一个 ArrayList,其元素类型为 String[],因为它恰好是这样声明的:

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

    public ArrayList<String> words;
...

有没有办法在 Clojure 中以编程方式获取 "type hint" 信息?

不,因为类型擦除。 https://docs.oracle.com/javase/tutorial/java/generics/erasure.html

关于您在 google 上删除的大量数据。

您可以根据列表中的数据使用简单的 hack。

例如你有一些字符串列表:

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

然后你可以得到物品类型:

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

此变通方法的缺点是您无法获得有关 freakhill 提到的擦除的空列表 b/c 的反射信息,但谁在乎空列表 ;)?

希望对您有所帮助。

感谢评论,我找到了this answer on the question Get generic type of java.util.List。从那里,我的示例代码的简单修改现在可以按需要工作:

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

Returns:

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