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

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

问题描述

我正在尝试使用此代码:

I'm experimenting with this code:

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(对象o)三倍。我希望方法选择考虑到真实的(不是声明的)参数类型。我错过了什么吗?有没有办法修改这个代码,以便它打印 foo(12) foo(foobar) foo(对象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天全站免登陆