java – 基于参数的真实类型的重载方法选择

我正在试验这段代码:

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中,动态方法分派仅针对调用该方法的对象,而不是针对重载方法的参数类型。

引用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).

http://stackoverflow.com/questions/1572322/overloaded-method-selection-based-on-the-parameters-real-type

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:java – 基于参数的真实类型的重载方法选择