我试图连接以运行查询以获取MongoDB中的所有记录,然后将这些记录转换为我作为调用类通用的引用对象类型的列表。该代码运行良好,并在Eclipse中达到了预期的结果,但是在maven构建过程中出现了编译错误,maven和eclipse都引用相同的JDK(1.8)。有人可以帮我解决这个问题吗
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
复制相同内容的完整信息是:-
更新:显式类型转换对象变量工作,但我仍然需要了解如何?
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();
}
}
当您尝试将对象投射到的特定对象Type
时report
,请尝试更改
T report = gson.fromJson(cursor.next().toJson(), modelObject.getClass());
至
T report = gson.fromJson(cursor.next().toJson(), (java.lang.reflect.Type) modelObject.getClass());
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句