我正在试验这段代码:
interface Callee {
public void foo(Object o);
public void foo(String s);
public void foo(Integer i);
}
class CalleeImpl implements Callee
public void foo(Object o) {
logger.debug("foo(Object o)");
}
public void foo(String s) {
logger.debug("foo(\"" + s + "\")");
}
public void foo(Integer i) {
logger.debug("foo(" + i + ")");
}
}
Callee callee = new CalleeImpl();
Object i = new Integer(12);
Object s = "foobar";
Object o = new Object();
callee.foo(i);
callee.foo(s);
callee.foo(o);
这会打印 foo(Object o)
三次。我希望方法选择考虑到真实的(不是声明的)参数类型。我错过了什么吗?有没有办法修改此代码,使其打印 foo(12)
、foo("foobar")
和 foo(Object o)
?
最佳答案
I expect the method selection to take in consideration the real (not the declared) parameter type. Am I missing something?
是的。你的期望是错误的。在 Java 中,动态方法分派(dispatch)只发生在调用该方法的对象上,而不发生在重载方法的参数类型上。
引用Java Language Specification :
When a method is invoked (§15.12), the number of actual arguments (and any explicit type arguments) and the compile-time types of the arguments are used, at compile time, to determine the signature of the method that will be invoked (§15.12.2). If the method that is to be invoked is an instance method, the actual method to be invoked will be determined at run time, using dynamic method lookup (§15.12.4).
关于java - 基于参数真实类型的重载方法选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1572322/