I'm trying to implement a generic cache class using the DualCache library. When instantiating the DualCache class one also needs to provide a serializer instance which itself is a generic class that should be of the same type as the DualCache its attached to.
我正在尝试使用DualCache库实现通用缓存类。在实例化DualCache类时,还需要提供一个序列化程序实例,该实例本身是一个通用类,应该与其附加的DualCache类型相同。
Simply put, I need to somehow pass T's class to the JSONSerializer
constructor as indicated in the code, but don't know how.
简单地说,我需要以某种方式将T的类传递给JSONSerializer构造函数,如代码所示,但不知道如何。
public class Cache<T> {
private boolean initialized = false ;
private ArrayList<Long> cachedItemList = new ArrayList<>() ;
private DualCache<T> dualCache ;
public void initialize(Context context) {
Log.e(DEBUG_TAG, "Cache/initialize") ;
if (!initialized) {
dualCache = new Builder<T>(ProjectInfo.cacheName, ProjectInfo.APP_VERSION)
.enableLog()
.useReferenceInRam(ProjectInfo.diskCacheSize, new SizeOf<T>() {
@Override
public int sizeOf(T object) {
return ProjectInfo.diskCacheSize / numCachedItems;
}
})
.useSerializerInDisk(ProjectInfo.diskCacheSize, true,
new JsonSerializer<>(T.class), context)
.build() ;
getCurrentCachedItemsList(context) ;
printCurrentItems(context) ;
initialized = true ;
}
}
}
1 个解决方案
#1
2
Assuming there is a constructor of the form JsonSerializer<T>(Class<T>)
, you will need to do exactly the same thing.
假设存在JsonSerializer
private final Class<T> clazz;
public Cache(Class<T> clazz) {
this.clazz = clazz;
}
public void initialize(Context context) {
...
new JsonSerializer<>(clazz), context)
#1
2
Assuming there is a constructor of the form JsonSerializer<T>(Class<T>)
, you will need to do exactly the same thing.
假设存在JsonSerializer
private final Class<T> clazz;
public Cache(Class<T> clazz) {
this.clazz = clazz;
}
public void initialize(Context context) {
...
new JsonSerializer<>(clazz), context)