gpt4 book ai didi

java - 如何从不可知函数调用多态函数?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:21:59 24 4
gpt4 key购买 nike

我有一个方法 foo

void foo (String x) { ... }
void foo (Integer x) { ... }

我想从一个不关心参数的方法中调用它:

void bar (Iterable i) {
...
for (Object x : i) foo(x); // this is the only time i is used
...
}

上面的代码提示 foo(Object)未定义,当我添加时

void foo (Object x) { throw new Exception; }

然后 bar(Iterable<String>)调用它而不是 foo(String)并抛出异常。

如何避免 bar(Iterable<String>) 有两个文本相同的定义?和 bar(Iterable<Integer>)

我以为我可以逃脱这样的事情

<T> void bar (Iterable<T> i) {
...
for (T x : i) foo(x); // this is the only time i is used
...
}

然后我得到 cannot find foo(T)错误。

最佳答案

您面临的问题是重载方法是在编译时绑定(bind)的。在您的示例中,编译器试图找出要调用的 foo() 方法。但是,您的示例中 x 的最强静态类型是 Object,并且没有方法 foo(Object),因此编译器说它无法调用适当的方法.

如果添加foo(Object)方法,无论x的实际运行时类型是什么,您将始终调用foo(Object)方法。

这个问题扩展到使用泛型。因为 T 可以是任何类型,所以你必须有一个泛型方法 foo(T) 否则你的代码将无法编译。但是,如果您添加该方法,您将失去让这些方法辨别不同参数类型的能力,因为只会调用 foo(T)

解决此问题的唯一方法是逐案检查并像建议的其他答案一样转换。除非参数类型是您定义的类,并且它们都可以实现一个通用接口(interface)。然后你可以这样做:

interface ArgumentType {
void callback(FooClass c);
}

class YourClassA implements ArgumentType {
void callback( FooClass c ) {
c.foo( this );
}
}

FooClass 仍然需要为 ArgumentType 的每个实现类提供一个 foo() 方法,但是这样您就可以进行选择类型不可知。

关于java - 如何从不可知函数调用多态函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11109429/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com