2017-09-28 162 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

相关问题