不兼容的类型:推理变量T具有不兼容的边界等式约束:捕获#1的?扩展java.lang.Object

我正在尝试连接以运行查询以获取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

关于复制同一个人的完整信息: –

《不兼容的类型:推理变量T具有不兼容的边界等式约束:捕获#1的?扩展java.lang.Object》

更新:明确键入一个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();
        }
    }

最佳答案 在尝试将对象强制转换为特定类型的报表时,请尝试更改

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

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