使用模板调用重载方法

Call overloaded method using template

共有三个class,ChildChildChildParent一个扩展另一个。我为大多数外部 class 使用模板调用方法,我想调用方法 doSomething 来打印 "CHILD"。而不是调用以前的方法。

class Test {
    public <T extends Parent> void doSomething(T input) {
        System.out.println("PARENT");
    }
    public <T extends Child> void doSomething(T input) {
        System.out.println("CHILD");
    }

    public <T extends Parent> void run(T input) { doSomething(input); }
}

class Main {
    public static void main(String[] args) {
        Test t = new Test();
        t.run(new ChildChild());
    }
}

是因为方法 运行 只为父 class 定义模板吗?

是的,当编译器擦除泛型类型参数时,它们会被它们的类型边界所取代,因此您的 run 方法变为:

public void run(Parent input) { doSomething(input); }

重载方法变为:

public void doSomething(Parent input) {
    System.out.println("PARENT");
}
public void doSomething(Child input) {
    System.out.println("CHILD");
}

因此 doSomething(Parent input) 被调用(请记住,方法重载分辨率是在编译时确定的,使用 compile-time 类型),无论您传递给 [= 的实例的运行时类型如何12=]方法。