I have a function that provide a map of classes annotated with a given annotation
void <A extends Annotation> ImmutableMap<Class<?>, A> find(Class<A> annotation, String packageBase) {
final ClassLoader loader = Thread.currentThread().getContextClassLoader();
return ClassPath.from(loader).getTopLevelClassesRecursive(packageBase).stream()
.filter(x -> x.load().getAnnotation(annotation) != null)
.collect(Collectors.collectingAndThen(Collectors
.toMap(ClassPath.ClassInfo::load, x -> x.load().getAnnotation(annotation)), ImmutableMap::copyOf));
}
I would like to make a general provider with a cache, like the following example
@Singleton
public class AnnotatedClassProvider {
private final Map<Class<? extends Annotation>, ImmutableMap<Class<?>, Object>> cache;
private final String basePackage;
public AnnotatedClassProvider(String basePackage) {
this.basePackage = basePackage;
this.cache = Maps.newHashMap();
}
public <A extends Annotation> ImmutableMap<Class<?>, A> get(Class<A> annotation) {
ImmutableMap<Class<?>, A> cached = cache.get(annotation);
if (cached != null)
return cached;
final ClassLoader loader = Thread.currentThread().getContextClassLoader();
cached = ClassPath.from(loader).getTopLevelClassesRecursive(basePackage).stream()
.filter(x -> x.load().getAnnotation(annotation) != null)
.collect(Collectors.collectingAndThen(Collectors
.toMap(ClassPath.ClassInfo::load, x -> x.load().getAnnotation(annotation)), ImmutableMap::copyOf));
this.cache.put(annotation, cached);
return (cached);
}
}
My problem: I don't find the way to replace Object
by a generic A
like in the get
function, for the following map:
private final Map<Class<? extends Annotation>, ImmutableMap<Class<?>, Object>> cache;
EDIT:
It compiles when I don't specify the map generics but I have to cast in the get method. Is there a way to avoid this?
private final Map<Class<? extends Annotation>, ImmutableMap> cache;
I think it should look like this
private final <A extends Annotation> Map<Class<A>, ImmutableMap<Class<?>, A>> cache;