识别使用反射的集合的替代类型

huangapple go评论80阅读模式
英文:

identifying substituted type of Collection using reflection

问题

我正在编写一个用于自动生成测试数据的小型库。它使用反射来创建任何类的随机实例。当其中一个类具有 List<T> 类型的字段时,我遇到了问题。我该如何找出 T 的类型?

在 IntelliJ 的“求值表达式”控制台中尝试了一些操作,我得出了以下结论:

private Class getGenericType(Field field){
    return ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0].getClass();
}

在弹出的控制台中,这似乎是有效的,但是当我将其放入代码并运行时,我收到了以下错误:

java.lang.InstantiationException: sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl 
at java.base/java.lang.Class.newInstance(Class.java:571)

有什么想法吗?我是否走在正确的道路上?

英文:

I'm writing a little library for automatic generation of test data. It uses reflection to be able to create a randomized instance of any class. I ran in to issues when one of the classes had a field of type List&lt;T&gt;. How do i find out the type of T?

playing around in IntelliJ's "evaluate expression" console, i came up with the following:

 private Class getGenericType(Field field){
        return ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0].getClass();
    }

which in seemed to work when evaluating in the popup console, but when I put it into the code and run, i get

java.lang.InstantiationException: sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl 
at java.base/java.lang.Class.newInstance(Class.java:571)

any ideas? am I even on the right path?

答案1

得分: 1

数组的第一个元素已经是一个Class实例,所以你可以这样做:

private Class getGenericType(Field field){
    return (Class)((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0];
}

编辑:这只在泛型类型是具体非泛型类型(例如List&lt;String&gt;)的情况下有效。对于更复杂的情况,你需要检查该类型是否可以实例化。请参考注释。

英文:

The first element of the array is already a Class instance so you can do this

 private Class getGenericType(Field field){
    return (Class)((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0];
 }

Edit: This would only work assuming the generic type is a concrete non-generic type as in List&lt;String&gt;. For more complex cases you will have to check if the type is one that can be instantiated. See comments.

huangapple
  • 本文由 发表于 2020年10月2日 23:22:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/64174184.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定