首页 > 解决方案 > 使用泛型的重载方法的莫名其妙的行为

问题描述

class My<T> {

    void overloadMethod(String s) {
        System.out.println("string");
    }

    void overloadMethod(Integer i) {
        System.out.println("integer");
    }

    void overloadMethod(T t) {
        System.out.println("t");
    }
}

public class MyClass01 {

    public static void main(String[] args) {
        String o = "abc";
        new My<String>().overloadMethod(o);
    }
}

这给出了以下错误:

/MyClass01.java:20: error: reference to overloadMethod is ambiguous
        new My<String>().overloadMethod(o);
                        ^
  both method overloadMethod(String) in My and method overloadMethod(T) in My match
  where T is a type-variable:
    T extends Object declared in class My
1 error

我期待“字符串”输出假设类型擦除将确保第三种方法是:

    void overloadMethod(Object t) {
        System.out.println("t");
    }

我在这里想念什么?

谢谢。

标签: javagenerics

解决方案


通过将泛型 实例class MyClass<T>化为特定的参数化类型new My<String>().overloadMethod(o);,您已经有效地声明了两个具有相同签名的方法:overloadMethod(String s).

这就是编译器错误试图告诉你的:“<em> error: reference to overloadMethod is ambiguous”。

„<em>...我在这里错过了什么?...</em>“</p>

因为您说:“<em>我期待“字符串”输出”,听起来您错误地假设您的声明以class My<T>某种方式使您的泛型方法overloadMethod(String s)具有参数多态性的能力。它没有。


推荐阅读