Guava cache generics error

醉酒当歌 提交于 2020-01-07 04:36:29

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!