java - Java 中使用原始类型方法的类型不匹配

标签 java generics

这里有几个与在 Java 中使用泛型类型不匹配相关的问题,但我找不到与我的情况相对应的任何内容。

我想知道为什么下面的代码会发生这个错误?

Type mismatch: cannot convert from element type Object to String

排队

for (String element : arg.someMethod())

但是如果

SomeInterface arg

改为

SomeInterface<?> arg

它有效。为什么列表参数类型没有连接接口(interface)类型参数会被删除?

import java.util.List;

public class TypeMismatchExample
{
    interface SomeInterface<P extends Object>
    {
        P someParametrizedMethod();

        List<String> someMethod();
    }

    void example(SomeInterface arg)
    {
        for (String element : arg.someMethod())
        {
            // do something
        }
    }
}

最佳答案

当您的代码中有原始类型时,该类中的所有泛型类型信息都会丢失 - 因此,编译器不知道 someMethod返回 List类型 String .

JLS 的相关部分:Raw Types

The type of a constructor (§8.8), instance method (§8.4, §9.4), or non-static field (§8.3) M of a raw type C that is not inherited from its superclasses or superinterfaces is the raw type that corresponds to the erasure of its type in the generic declaration corresponding to C.

既然您将方法参数声明为 SomeInterface ,这是一种原始类型,您无法利用泛型 someMethod ,即使其泛型类型参数与 P 不同。 .

关于java - Java 中使用原始类型方法的类型不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23667920/

相关文章:

java - 我应该导入哪个 .jar 以便 "import com.android.widget"解析为类型?

java - 如何在部署 WAR 文件时传递参数?

java - 定义package时为目标命名空间定义了多个<schemaBindings>

java - 如何找到要跳转到的页面。我使用 PDFBox 2.0.0 和 PDActionGoTo

typescript - 如何使函数重载通用以强类型化其实现参数?

java - 如何将 Json 属性名称映射到 Java 字段值

swift - 仅类协议(protocol)作为具有 AnyObject 约束的关联类型的类型别名

java - JDK 1.7 打破了向后兼容性? (泛型)

generics - 为一种特定的泛型类型专门化方法

具有匿名内部类的 Java 比较器接口(interface) NullsLast