我今天遇到了一种情况,Java 没有调用我期望的方法——这是最小的测试用例:(很抱歉,这似乎是做作的——“现实世界”的场景要复杂得多,而且更有意义从“你为什么要这样做?”的角度来看。)
我对为什么会发生这种情况特别感兴趣,我不在乎重新设计的建议。我感觉这是在 Java Puzzlers 中,但我手边没有我的副本。
请参阅下面 Test<T>.getValue() 中的特定问题:
public class Ol2 {
public static void main(String[] args) {
Test<Integer> t = new Test<Integer>() {
protected Integer value() { return 5; }
};
System.out.println(t.getValue());
}
}
abstract class Test<T> {
protected abstract T value();
public String getValue() {
// Why does this always invoke makeString(Object)?
// The type of value() is available at compile-time.
return Util.makeString(value());
}
}
class Util {
public static String makeString(Integer i){
return "int: "+i;
}
public static String makeString(Object o){
return "obj: "+o;
}
}
这段代码的输出是:
obj: 5