We are trying to create a rudimentary implementation of a Cache
in Java. For this, we have created an annotation @Cached
defined as:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Cached {
<T> Class<T> keyClass();
<V> Class<V> valueClass();
String cacheId();
}
This leads to an error: @interface members may not have type parameters
. This however is needed as we would like to typecast the values of the returned method and store them in the cache. We are using AspectJ
for intercepting the method calls whose results need to be cached.
What is the other way in which we can achieve the result? Since not all methods have the same signature, we have to rely on the methods marked @Cached
for our cache implementation.
UPDATE Here is the class that stores data in the cache:
public class Cache<K extends Serializable, V> {
private Map<K, CacheEntry<V> cache;
// Some other fields and accessors
}
The class CacheEntry
is defined as:
public class CacheEntry<V> {
private V value;
// Some other fields used for invalidating the cache entry and accessors
}
Now when accessing the cache, I would like to do something like this:
cache.getCache().values().stream()
.map(value -> cached.valueClass().cast(value))
.collect(Collectors.toList());
In above code, cached
is the reference of @Cached
annotation used on the method as:
@Cached(keyClass = Long.class, valueClass = Person.class, cacheId = "personCache")
List<Person> findAll();