基于参数真实类型的重载方法选择 [英] Overloaded method selection based on the parameter's real type

查看:32
本文介绍了基于参数真实类型的重载方法选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在试验这段代码:

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)代码>?

This prints foo(Object o) three times. I expect the method selection to take in consideration the real (not the declared) parameter type. Am I missing something? Is there a way to modify this code so that it'll print foo(12), foo("foobar") and foo(Object o)?

推荐答案

我希望方法选择考虑到真实的(不是声明)参数类型.我失踪了吗什么?

I expect the method selection to take in consideration the real (not the declared) parameter type. Am I missing something?

是的.你的期望是错误的.在 Java 中,动态方法调度只针对调用该方法的对象发生,而不针对重载方法的参数类型.

Yes. Your expectation is wrong. In Java, dynamic method dispatch happens only for the object the method is called on, not for the parameter types of overloaded methods.

引用 Java 语言规范:

调用方法时(第 15.12 节),实际参数的数量(以及任何显式类型参数)和 参数的编译时类型在编译时用于确定方法的签名将被调用(第 15.12.2 节).如果要调用的方法是实例方法,实际方法被调用将在运行时确定时间,使用动态方法查找(第 15.12.4 节).

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

这篇关于基于参数真实类型的重载方法选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆