【问题标题】:Intellij not recognizing wrong return typeIntellij 无法识别错误的返回类型
【发布时间】:2022-01-12 12:26:27
【问题描述】:

我有这个方法:

public <T extends CacheResult> T get(Object key, CacheDefinition cacheDefinition) {
    return load(key, cacheDefinition.name(), cacheDefinition.getTypeReference());
}

现在我的 IDE 抱怨(正如预期的那样,这是正确的)关于这一行,因为返回类型应该是 CacheResult

User user = spxCacheManager.get(username, CacheDefinition.USERS_BY_USERNAME);

我目前不明白的是,IDE(IntelliJ)没有抱怨这个:

List<User> usersFromCache = spxCacheManager.get(username, CacheDefinition.USERS_BY_USERNAME);

这实际上是错误的。我在这里错过了什么?

【问题讨论】:

    标签: java intellij-idea


    【解决方案1】:

    之所以有效,是因为T 被推断为交集类型 - List&lt;User&gt; &amp; CacheResult &amp; Object。毕竟,为什么一个类不能同时实现List&lt;User&gt;实现/扩展CacheResult?这种类型肯定是可以的!

    您可以通过编写一个玩具程序并使用--debug=verboseResolution=all 选项来看到这种情况:

    import java.util.List;
    
    public class Main {
    
      public static void main(String[] args) {
        List<User> u = new Main().get();
      }
    
      public <T extends CacheResult> T get() {
        return null;
      }
    }
    
    interface CacheResult {}
    class User implements CacheResult {}
    

    javacverboseResolution=all 将输出:

      instantiated signature: ()INT#1
      target-type: List<User>
      where T is a type-variable:
        T extends CacheResult declared in method <T>get()
      where INT#1 is an intersection type:
        INT#1 extends Object,List<User>,CacheResult
    

    您也可以关注the process of how Java does type inference。最终(在“分辨率”中的某个位置),您将到达需要找到ObjectList&lt;User&gt;CacheResult最大下限(“glb”)的点,并且该类型正是它们的交集类型,定义为here

    另一方面,如果CacheResult 是一个类,并且您将方法结果分配给的类型是一个不相关的类,则您的代码将无法编译,因为没有类可以从两个不相关的类继承。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-05
      • 1970-01-01
      • 2021-10-18
      • 2017-08-26
      相关资源
      最近更新 更多