2014-01-06 115 views
1

比較類型我得到這個錯誤:使用反射

incomparable types: Class and String where CAP#1 is a fresh type-variable: CAP#1 extends Object from capture of ?

Object object; 
Field[] fields = object.getClass().getDeclaredFields(); 
for (int i = 0; i < fields.length; i++) { 
    if (fields[i].getType() == String) { //On this line the compiler error is displayed 
     //Can't get in here    
    } 
} 

我以爲我是在if語句比較兩個相同的類的?

回答

4

getType返回一個類,因此您必須將其與Class進行比較。要獲得String的課程,您必須使用String.class

if (fields[i].getType() == String.class) { 
     //Now you can get in here!    
}