java - 所需类型与找到的类型相同

标签 java types

我想这样做:

    Foo<String> foo = new Foo<>();
    Foo<String>.Bar fooBar = foo.new Bar();

    fooBar.doSomething("this works!");

但是前两行在一行中,例如:

Foo<String>.Bar fooBar2 = new Foo<>().new Bar();
fooBar2.doSomething("The above line gives: incompatible types. Required: Foo.Bar Found: Foo.Bar");

但是第一行失败了。我得到:

incompatible types.

Required: Foo.Bar

Found: Foo.Bar

这是为什么?

public class Foo<T> {


    public class Bar extends SomeOtherClass<T> {

        public void doSomething(T t) {

        }

    }

}

最后一节课:

public class SomeOtherClass<T> {
}

最佳答案

在某些情况下,Java 无法很好地处理类型推断(当人们认为它应该处理时)。这是其中一种情况。

如果您显式地将类型传递给 new 调用,它将编译:

Foo<String>.Bar fooBar2 = new Foo<String>().new Bar();

关于java - 所需类型与找到的类型相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30654656/

相关文章:

c# - HashPasswordForStoringInConfigFile()的输出是什么格式,如何存储最好?

java - 如何在 Java REST 服务中验证 XML 输入非空属性?

java - Jmeter 插件管理器

java - Emacs-公司 : An error occurred in auto-begin Invalid function

java - 避免字符串中出现 : and , 的正则表达式模式

java - 类型不匹配无法从 String 转换为 int

java - Java 中的二进制补码运算符

javascript - 修复 Typescript 中的类型

C 语言 : Since there is no "byte" primitive, 是使用 "char"的确切等价物吗?

sql - postgres中数组聚合的算术运算