mardi 18 avril 2017

Java create generic class with generic type

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.

Simply put, I need to somehow pass T's class to the JSONSerializer constructor as indicated in the code, but don't know how.

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 ;
        }
    }
}





Aucun commentaire:

Enregistrer un commentaire