[英]@Query did not match expected type [java.util.Collection (n/a)]
[英]Java: How to check if a Field is of type java.util.Collection
我有一個實用程序方法,遍歷各種類並遞歸檢索字段。 我想檢查該字段是否為Collection。 以下是一些示例代碼:
void myMethod(Class<?> classToCheck)
Field[] fields = classToCheck.getDeclaredFields();
for(Field field:fields)
{
// check if field if a Collection<?>
}
在此先感謝您的幫助。
if (Collection.class.isAssignableFrom(field.getType())) {
}
你應該使用Class.isAssignableFrom
:
if (Collection.class.isAssignableFrom(field.getType())
...
使用getType()
方法
Field field = ...;
if ( Collection.class.isAssignableFrom( field.getType() ) ){
//do something with your collection
}
//這執行if
List<String> cashType = split(" ,AlL ");
if(cashType instanceof Collection){
System.out.println("cashType instanceof Collection");
}else{
System.out.println("cashType is not instanceof Collection");
}
//這執行其他操作
List<String> cashType = split(" ,AlL ");
if(cashType instanceof Hashtable){
System.out.println("cashType instanceof Collection");
}else{
System.out.println("cashType is not instanceof Collection");
}
for(Field field:fields) { // check if field if a Collection
Object myInstance = field.get(classInstance);
// where classInstance is the instance in which the fields is stored
if(myInstance instanceof Collection) {
//Do your thing
}
}
這將測試字段'field'(對象classInstance)引用的實際對象是否實現Collection。 如果要測試聲明的Field類型是否實現Collection,那么它將是不同的。
您可以通過以下方式使用getType()
:
if (field.getType().equals(Collection.class) {
// Do something
}
這僅在字段聲明為Collection
時才有效。 如果該字段是Collection的子類型(例如List
或Vector
,則無效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.