【发布时间】:2020-10-23 08:37:12
【问题描述】:
我正在尝试通过以下代码使用 java 15 中的泛型类
@Singleton
public class GenericRepository<T> implements IGenericRepository<T>{
private final MongoClient mongoClient;
public GenericRepository(MongoClient mongoClient) {
this.mongoClient = mongoClient;
}
public MongoCollection<T> getCollection(String collectionName) {
return mongoClient
.getDatabase("main")
.getCollection(collectionName, T.class);
}
}
我不能使用T.class,我该如何解决这个问题
我找到的解决方案
@Singleton
public class GenericRepository<T> implements IGenericRepository<T>{
private final MongoClient mongoClient;
private final Class<T> typeParameterClass;
public GenericRepository(MongoClient mongoClient, Class<T> typeParameterClass) {
this.mongoClient = mongoClient;
this.typeParameterClass = typeParameterClass;
}
public MongoCollection<T> getCollection(String collectionName) {
return mongoClient
.getDatabase("main")
.getCollection(collectionName, this.typeParameterClass);
}
}
由于使用这个解决方案是相当多的代码,有没有更好的方法来做到这一点?
【问题讨论】:
-
泛型在 Java 的运行时被删除,这就是为什么你不能使用
T.class。您找到的解决方案通常是使用的解决方案(但请注意,即使解决方案也不是完全类型安全的,例如List<U>不能完全由Class对象表示)。 -
原版 Java 中没有。您是否有机会使用 Spring?
-
我正在使用 Micronaut 框架,抱歉没有使用 spring
-
请注意,将泛型类型用作单例对我来说似乎很奇怪。它是泛型的事实暗示了不同的参数化,但将其设为单例仅暗示了一种参数化(在这种情况下,为什么要使类型泛型?)。
-
除了@Slaw 关于在单例中使用泛型的评论之外,您找到的解决方案似乎是执行此操作的正确方法。与其将 this 传递给构造函数,不如将其传递给类型转换的方法。在这两者之间,最好看一下配置
mongoClient以使用main作为数据库并调用其getCollection的方法。这应该完全消除整个类