检索集合的类型
所以我在 Java 中有类似以下内容:
private List<SomeType>variable;
// ....variable is instantiated as so ...
variable = new ArrayList<SomeType>();
// there's also a getter
public List<SomeType> getVariable() { /* code */ }
我希望能够以编程方式找出 variable
是 SomeType
的集合。我读到这里,我可以从方法 getVariable()
但有没有办法直接从 variable
中判断?
我已经能够根据链接中的信息从 getter 方法检索 SomeType
。我还通过 SurroundingClass.getClass().getDeclaredFields()
成功检索了周围类的所有字段,但这并没有告诉我它是 List
编辑:根据 bmargulies 的回应,执行以下操作将实现我想要的:
Field[] fields = SurroundingClass.getDeclaredFields();
/* assuming it is in fields[0] and is a ParameterizedType */
ParameterizedType pt = (ParameterizedType) fields[0].getGenericType();
Type[] types = pt.getActualTypeArguments();
/* from types I'm able to see the information I've been looking for */
So I have something like the following in Java:
private List<SomeType>variable;
// ....variable is instantiated as so ...
variable = new ArrayList<SomeType>();
// there's also a getter
public List<SomeType> getVariable() { /* code */ }
What I would like to be able to do is figure out that variable
is a collection of SomeType
programmatically. I read here that I can determine that from the method getVariable()
but is there any way to tell directly from variable
?
I have been able to retrieve SomeType
from the getter method based on the information in the link. I have also been successful in retrieving all the fields of the surrounding class via SurroundingClass.getClass().getDeclaredFields()
but this doesn't tell me that it is List<SomeType>
.
EDIT: Based on bmargulies's response doing the following will achieve what I want:
Field[] fields = SurroundingClass.getDeclaredFields();
/* assuming it is in fields[0] and is a ParameterizedType */
ParameterizedType pt = (ParameterizedType) fields[0].getGenericType();
Type[] types = pt.getActualTypeArguments();
/* from types I'm able to see the information I've been looking for */
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于类型擦除,您无法从实例中获取此信息。在运行时,
XXX
实际上只是XXX
。除非班级做出特殊安排来存储 T 的班级参考,否则它会完全消失。您可以通过 getDeclaredFields() 获取它。您必须在 Field 上调用 getGenericType,而不是 getType,然后必须对 ParameterizedType 进行一些转换,然后向其询问所需的参数。
You can't get this from the instance, due to type erasure. At runtime,
XXX<T>
is really justXXX
. Unless the class makes special arrangements to store a Class reference for the T, it's completely and totally gone.You can get it from getDeclaredFields(). You have to call getGenericType on the Field, not getType, and then you have to do some casting to ParameterizedType and then ask it for the parameter you want.
您可以通过查看 Collection 中的元素之一来获取 SomeType
You can get SomeType by looking at one of the elements in the Collection