简体   繁体   English

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

[英]Java calling method on all objects of specific type

Okay, the title is a little bit cryptic, an example will show better what I mean, suppose the following structure: 好的,标题有点含糊,假设下面的结构,一个示例可以更好地说明我的意思:

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();
    }
}

This code has been heavily simplified, the classes A , B and C implement methodCall() obviously, but there is no need to explicitely show that in the code. 该代码已进行了大幅简化, ABC类显然实现了methodCall() ,但是无需在代码中显式地表明这一点。

What I want to ask is the following: 我想问的是以下内容:
Is there a way to tell Java to generate my doSomeMainMethod method? 有没有办法告诉Java 生成我的doSomeMainMethod方法? I want to tell Java to call methodCall() on all objects of type I in class Main . 我想告诉Java在类Main对所有类型I对象调用methodCall()

Preferably without the use of reflection, because with reflection I think it is possible or if reflection is needed, is there a way to wrap it up such that it at least looks non-hackish? 最好不要使用反射,因为我认为使用反射是可能的,或者如果需要反射,是否有办法将其包裹起来,使其至少看起来像是没有黑漆的? Ofcourse it needs to be safe (as safe as possible) aswell. 当然,它也需要安全(尽可能安全)。

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();
    }
}

If you want the method to be generated then you can use ASM generation or (probably simpler option) implement your own AnnotationProcessor. 如果要生成方法,则可以使用ASM生成或(可能更简单的选项)实现自己的AnnotationProcessor。 With the second option you should annotate your classes and then scan for this annotation in compile time and generate decired method. 使用第二个选项,您应该对您的类进行注释,然后在编译时扫描该注释并生成所需的方法。

interface I {
  void methodCall();
  List<I> INSTANCES = new ArrayList<I>();
}

Now, in every constructor of classes that implements interface I, do this: 现在,在实现接口I的每个类的构造函数中,执行以下操作:

I.INSTANCES.add(this);

In main: 在主要方面:

for (I i : I.INSTANCES) {
  // do something with every instance of I
}

EDIT: This will add all instances of I. To limit it to the objects created in Main, let´s add a parameter, createdBy. 编辑:这将添加I的所有实例。为了将其限制为在Main中创建的对象,我们添加一个参数createdBy。 It is not quite elegant, but it is just Java, no Reflection ... 它不是很优雅,但只是Java,没有反射...

public A(Class createdBy) {
  if (createdBy.equals(Main.class) {
    I.INSTANCES.add(this);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM