gpt4 book ai didi

Java对特定类型的所有对象调用方法

转载 作者:太空宇宙 更新时间:2023-11-04 15:10:48 25 4
gpt4 key购买 nike

好吧,标题有点神秘,一个例子会更好地说明我的意思,假设结构如下:

interface I { 
methodCall();
}

class A implements I {
}

class B implements I {
}

class C implements I {
}

class Main {
private A a;
private B b;
private C c;

//other interesting stuff

void doSomeMainMethod() {
a.methodCall();
b.methodCall();
c.methodCall();
}
}

这段代码已经被大大简化了,类 ABC 显然实现了 methodCall() ,但无需在代码中明确显示。

我想问的是:
有没有办法告诉 Java 生成我的 doSomeMainMethod 方法?我想告诉 Java 对 Main 类中所有 I 类型的对象调用 methodCall()

最好不使用反射,因为使用反射我认为这是可能的,或者如果需要反射,有没有办法将其包装起来,使其至少看起来不那么黑客?当然它也需要安全(尽可能安全)。

最佳答案

class Main {
private A a;
private B b;
private C c;
private I[] instances = new I[]{a, b, c};

//other interesting stuff

void doSomeMainMethod() {
for(I instance : instances) {
instance.methodCall();
}
}

关于Java对特定类型的所有对象调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21349994/

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