2017-09-28 164 views
3

我想連接運行一個查詢來獲取MongoDB中的所有記錄,然後將記錄轉換爲引用對象類型的列表,我將它作爲我的調用類的泛型。代碼運行良好,在Eclipse中實現了期望的結果,但在maven構建過程中出現了編譯錯誤,maven和eclipse都引用了相同的JDK(1.8)。有人可以幫我解決這個問題不兼容的類型:推理變量T具有不兼容的邊界相等約束:capture#1 of? extends java.lang.Object

public class MongoPersistenceImpl<T> { 

MongoDatabase database=(MongoDatabase)MongoConnectImpl.getInstance().getConnection(); 

public List<T> getAll(T modelObject){ 
     MongoCollection<Document> collection=database.getCollection(MongoConnectImpl.MONGO_COLLECTION); 
     List<T> reportList=new ArrayList<>(); 
     Gson gson=new Gson(); 
     MongoCursor<Document> cursor = collection.find().iterator(); 
     try { 
      while (cursor.hasNext()) { 
       T report=gson.fromJson(cursor.next().toJson(),modelObject.getClass()); 
       reportList.add(report); 
      } 
      return reportList; 
     }catch(Exception e){ 
      CatsLogger.printLogs(3, "30016", e, MongoPersistenceImpl.class,new Object[]{"get all"}); 
      return null; 
     } finally { 
      cursor.close(); 
     } 
    } 

} 

日誌: -

[ERROR] COMPILATION ERROR : 
[INFO] ------------------------------------------------------------- 
[ERROR] incompatible types: inference variable T has incompatible bounds 
    equality constraints: capture#1 of ? extends java.lang.Object 
    upper bounds: T,java.lang.Object 

上重現同一個幸福完整的消息: -

enter image description here

UPDATE:明確地類型轉換一個對象變量工作,但我仍然編輯瞭解如何?

public List<T> getAll(T modelObject){ 
     MongoCollection<Document> collection=database.getCollection(MongoConnectImpl.MONGO_COLLECTION); 

     List<T> reportList=new ArrayList<T>(); 
     Gson gson=new Gson(); 
     MongoCursor<Document> cursor = collection.find().iterator(); 
     try { 
      while (cursor.hasNext()) { 
       Object rep=gson.fromJson(cursor.next().toJson(),modelObject.getClass()); 
       T report=(T)rep;//explicit type cast 
       reportList.add(report); 
      } 
      return reportList; 
     }catch(Exception e){ 
      CatsLogger.printLogs(3, "30016", e, MongoPersistenceImpl.class,new Object[]{"get all"}); 
      return null; 
     } finally { 
      cursor.close(); 
     } 
    } 
+0

在MAVE建立_javac_使用,而Eclipse的IDE使用它自己的編譯器來增量編譯Java代碼。 _javac_的錯誤信息不是非常有用的信息(例如,代碼中沒有「capture#1」)。你確定代碼是由代碼片段造成的嗎?你是否也可以使用'MongoPersistenceImpl '來顯示代碼? – howlger

+0

@howlger錯誤中有行號,它指向'T report = gson.fromJson(cursor.next()。toJson(),modelObject.getClass());'作爲錯誤的行 – SakshamB

回答

1

當你試圖對象轉換的report特定Type,嘗試改變

T report = gson.fromJson(cursor.next().toJson(), modelObject.getClass()); 

T report = gson.fromJson(cursor.next().toJson(), (java.lang.reflect.Type) modelObject.getClass()); 
+1

感謝您的回答..它的工作..你能請詳細說明確切的問題是什麼? – SakshamB

+0

問題是您嘗試投射課程的類型未知。當您將其轉換爲'Type'時,您可以爲Java中的任何類型提供超級接口,其中T可以在您的泛型定義中。 – nullpointer

+1

aah ..好的..這就是爲什麼明確類型鑄造對象後工作..謝謝:) – SakshamB

相關問題