番石榴缓存泛型错误

时间:2017-09-20 07:27:37

标签: generics guava

尝试创建番石榴缓存时出现奇迹错误:

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编译错误:

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>

番石榴版是20.0 java版本是1.6

使用java 1.8和guava 23.0时 - 没关系!

问题是我必须只使用1.6 java

2 个答案:

答案 0 :(得分:1)

您可以使用的一些解决方法:

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();

答案 1 :(得分:1)

正如您所提到的那样,它适用于JDK 8,因为enhancements in type inference引入了that version

在JDK 6上,您会遇到类型不匹配:

found   : ConcurrentMap<Object, Object>
required: ConcurrentMap<Long, Object>

因为在没有类型提示的情况下无法推断出cache的类型。