英文:
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<T>
. 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<String>
)的情况下有效。对于更复杂的情况,你需要检查该类型是否可以实例化。请参考注释。
英文:
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<String>
. For more complex cases you will have to check if the type is one that can be instantiated. See comments.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论