问题
Magical error appears when trying to create guava cache:
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import java.util.concurrent.ConcurrentMap;
public class Main {
private static ConcurrentMap<Long, Object> cache = CacheBuilder
.newBuilder()
.build(new CacheLoader<Long, Object>() {
@Override
public Object load(Long key) throws Exception {
return null;
}
}).asMap();
}
java compile error:
Error:(17, 21) java: C:\JavaWorkspace\untitled\src\...\Main.java:17: incompatible types
found : java.util.concurrent.ConcurrentMap<java.lang.Object,java.lang.Object>
required: java.util.concurrent.ConcurrentMap<java.lang.Long,java.lang.Object>
guava version is 20.0 java version is 1.6
while using java 1.8 and guava 23.0 - it is OK!
The problem is I have to use only 1.6 java
回答1:
Some workaround you can use:
private static LoadingCache<Long, Object> cache = CacheBuilder
.newBuilder()
.build(new CacheLoader<Long, Object>() {
@Override
public Object load(Long key) throws Exception {
return null;
}
});
private static ConcurrentMap<Long, Object> cacheMap = cache.asMap();
回答2:
As you mentioned it works on JDK 8 because of enhancements in type inference which were introduced in that version.
On JDK 6 you get type mismatch:
found : ConcurrentMap<Object, Object>
required: ConcurrentMap<Long, Object>
because cache
's type cannot be inferred without a type hint.
来源:https://stackoverflow.com/questions/46315760/guava-cache-generics-error