Java:如何检查字段是否属于 java.util.Collection 类型
我有一个实用程序方法,可以遍历各种类并递归地检索字段。我想检查该字段是否是一个集合。 这是一些示例代码:
void myMethod(Class<?> classToCheck)
Field[] fields = classToCheck.getDeclaredFields();
for(Field field:fields)
{
// check if field if a Collection<?>
}
提前感谢您的帮助。
I have a utility method that goes through various classes and recursively retrieves the fields. I want to check if that field is a Collection.
Here is some sample code:
void myMethod(Class<?> classToCheck)
Field[] fields = classToCheck.getDeclaredFields();
for(Field field:fields)
{
// check if field if a Collection<?>
}
Thanks in advance for the help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您应该使用Class.isAssignableFrom:
You should use
Class.isAssignableFrom
:使用
getType()
方法Using the
getType()
method//这里执行if
//这里执行else
//This execute if
//This executes else
您可以按以下方式使用
getType()
:仅当字段声明为
Collection
时,此方法才有效。如果该字段是 Collection 的子类型,例如List
或Vector
,则它将不起作用。You can use
getType()
in the following way:This will only work if the field is declared as a
Collection
. It will not work if the field is a subtype of Collection, such asList
orVector
.这测试字段“field”(对象 classInstance 的)引用的实际对象是否实现 Collection。如果您想测试 Field 的声明类型是否实现 Collection,那么情况会有所不同。
This tests whether the actual object referred to by the field 'field' (of the object classInstance) implements Collection. If you want to tests whether the declared type of Field implements Collection then that will be different.