java Intellij 警告 - 通用未检查分配

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12566757/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 09:24:13  来源:igfitidea点击:

Intellij Warning - Generic Unchecked Assignment

javagenericsunchecked

提问by EdgeCase

Possible Duplicate:
Java Generics, how to avoid unchecked assignment warning when using class hierarchy?

可能的重复:
Java 泛型,如何在使用类层次结构时避免未经检查的赋值警告?

Intellij is giving me the warning below. Not sure how to resolve it, or even if I need to resolve it. The warning details says it only applies to JDK 5, and I am using 6. I am wondering if I need to respond to this, and if so, how?

Intellij 给了我下面的警告。不知道如何解决它,或者即使我需要解决它。警告细节说它只适用于 JDK 5,而我使用的是 6。我想知道我是否需要对此做出回应,如果需要,如何回应?

Method call causing warning

方法调用导致警告

List<T> refObject = cache.getCachedRefObject(cacheKey, List.class);

Method being called

被调用的方法

public  <T> T getCachedRefObject(String objectKey, Class<T> type) {
    return type.cast(refObjectCache.get(objectKey));
}

Warning details

警告详情

Unchecked Assignment
JDK 5.0 only. Signals places where an unchecked warning is issued by the compiler, for example:
    void f(HashMap map) {
        map.put("key", "value");
    }

采纳答案by millimoose

Having played with super type tokens for this, I don't think you can make this type-safe without making extra methods to retrieve collections from your cache and verifying if their contents are of the correct type.

为此使用了超类型令牌,我认为如果不使用额外的方法从缓存中检索集合并验证它们的内容是否为正确类型,就无法使这种类型安全。

Your options are:

您的选择是:

  1. Doing the above, which seems laborious
  2. Suppress the unchecked cast in client code if you know it's correct.
  3. Replace the client code with List<?> refObject = cache.getCachedRefObject(cacheKey, List.class);
  1. 做上面的,似乎很费力
  2. 如果您知道它是正确的,则禁止在客户端代码中进行未经检查的强制转换。
  3. 将客户端代码替换为 List<?> refObject = cache.getCachedRefObject(cacheKey, List.class);

The only type-safe variant of these is 3., in that it prevents you from doing operations that the compiler can't prove are type-safe. The obvious downside is that you might want to do some of these operations anyway.

其中唯一的类型安全变体是 3.,因为它阻止您执行编译器无法证明是类型安全的操作。明显的缺点是您可能想要执行其中一些操作。

回答by Peter Lawrey

Sounds like you have an old version of IntelliJ. This warning really means Java 5.0+ and AFAIK this was changed when IntelliJ supported Java 6 so the warning was there but didn't say "JDK 5.0 only" (it now has support for Java 8)

听起来你有一个旧版本的 IntelliJ。这个警告真的意味着 Java 5.0+ 和 AFAIK 这在 IntelliJ 支持 Java 6 时改变了所以警告在那里但没有说“仅 JDK 5.0”(它现在支持 Java 8)