1

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 ;
        }
    }
}
Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
Paghillect
  • 822
  • 1
  • 11
  • 30
  • 1
    `T` is erased at runtime. In order to do this, you'll need to store T's class somewhere when intiaizling either `Cache` or `DualCache`. Or, if you can get an instance of T from `Cache` or `DualCache`, you can use that instance to determine the class. – Christopher Schneider Apr 18 '17 at 13:40
  • 3
    Due to type erasure you won't have access to the type of `T` at runtime so you might have to pass a `Class` to `initialize()` and pass that to the `JsonSerializer`. Alternatively pass it to the `Cache` constructor and store it in the instance. – Thomas Apr 18 '17 at 13:41
  • http://stackoverflow.com/questions/3403909/get-generic-type-of-class-at-runtime – Andremoniy Apr 18 '17 at 13:52

1 Answers1

2

Assuming there is a constructor of the form JsonSerializer<T>(Class<T>), you will need to do exactly the same thing.

private final Class<T> clazz;

public Cache(Class<T> clazz) {
    this.clazz = clazz;
}

public void initialize(Context context) {
    ...
                        new JsonSerializer<>(clazz), context)
Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305