java - 由于 Java 泛型,我无法编译 Guava 的缓存构建器

标签 java generics guava

我有以下简短的自包含代码,在编译时显示错误。我拼命地试图让它编译。我通常不会再遇到泛型问题,但好吧,我放弃了这个,我请求团队的帮助。

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

public class CacheWithGenericsDoesNotCompile {

  // Class definition can't be modified
  static class Resource<T extends Resource<T>> {}

  // Class definition can't be modified
  static class ResourceType<T extends Resource<T>> {
    public ResourceType(Class<T> type) {}
  }

  // Variable definition may be modified
  static LoadingCache<Class<? extends Resource<?>>, ResourceType<? extends Resource<?>>> cache = CacheBuilder.newBuilder().build(
      new CacheLoader<Class<? extends Resource<?>>, ResourceType<? extends Resource<?>>>() {
        @Override public ResourceType<? extends Resource<?>> load(Class<? extends Resource<?>> key) throws Exception {
          return new ResourceType<? extends Resource<?>>(key);
        }
    });

  // Method definition can't be modified, method content may.
  @SuppressWarnings("unchecked")
  static <T extends Resource<T>> ResourceType<T> getResourceType(Class<T> type) {
    return (ResourceType<T>)cache.getUnchecked(type);
  }
}

编译失败的行是:

return new ResourceType<? extends Resource<?>>(key);

我知道为什么会失败:我可能不会写 new Xxxx<...>带有问号 ( ? )。我只是不能以不同的方式编写这一行来编译其他行。

Resource 的情况下,我有一个后备解决方案没有泛型,但在可能的限制下我想保留 Resource与泛型。

我对 LoadingCache 的泛型没有限制除了我需要像 getResourceType(Class) 中那样调用它.

那么...我该如何修复这段代码?

最佳答案

一些忽略警告的解决方案:

  static LoadingCache<Class<? extends Resource<?>>, ResourceType<? extends Resource<?>>> cache = CacheBuilder.newBuilder().build(
      new CacheLoader<Class<? extends Resource<?>>, ResourceType<? extends Resource<?>>>() {
        @SuppressWarnings({ "rawtypes", "unchecked" })
        @Override public ResourceType<? extends Resource<?>> load(Class<? extends Resource<?>> key) throws Exception {
          return new ResourceType(key);
        }
    });

根据 @John B 的建议在评论中。由于 type-erasure,此代码在运行时 与问题中的代码没有区别.

关于java - 由于 Java 泛型,我无法编译 Guava 的缓存构建器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15382520/

相关文章:

java - 在 Java 中创建 .obj 文件

java - 如何为 Jetty 的 Maven Cargo 插件指定 jetty-env.xml 文件?

多维数组中的 Java 显式声明

c# - C#中的通用缓存

java - Google Guava 可选 - 如何短路多个链式表达式

Java反编译器与Java反汇编器

ios - Swift - 将参数从非泛型函数传递到泛型函数

java - 泛型代码错误

java - Guava 基于策略的缓存

java - 在 Java 中通过 Maps.newHashMapWithExpectedSize(...) 限制 Map 的大小会导致冲突