[Java] Invoking Method from Multi-Classes

Hello folks. I’m experimenting with Java and just want to test something out. I came across a pretty interesting concept that I have not yet found a working solution for.

Image here since new users cant post images apparently.

If you need some explanations: All of the middle class implements the interface with the method calc() which returns a value but we wont get into that. Method getValue() will try to invoke all of the calc() methods from the classes (the external class is a thought of an add-on), and get combine their return values into int value.

An idea I have is using some reflection to look up the class name, but I thought that maybe inefficient. Using HashMaps to register the classes, but I have no idea how to pull the classes out from the set and invoke a method from them. Just some thoughts.

I haven’t got into advance Java programming yet, but this is an interesting concept I would like to solve. Thank you for reading.

What do you mean by that?

Ps: You can send me a pm in German language if you want

Getting all the values from those invoked calc() methods, then put it in the value value.

Are you just trying to get (N)Classes and invoke the clac() method? And does it matter where or how the class is stored?

Iterate through the classes and for each class do the following:

  1. Call newInstance() to create an instance of the class (requires the class to have a nullary constructor)
  2. Cast the Object from newInstance() to your interface and invoke the method from there
  3. Take the result of that method, do whatever you want, and move on to the next class
2 Likes

Why don’t you just have them instantiated and then added to a list? Then you can iterate over that and run calc on every one.

Your description sounds like you could use the observer pattern for this. Using reflection just to call a method on a list of known object is a bit of an overkill, I’d say.

I didn’t understand the goal you want to achieve here yet, but maybe you want to have a look at the visitor pattern as well. If you plan to add more methods like the mentioned calc() it could be worth to split the algorithm from the classes.

Both patterns are documented very good and pretty common in Java applications. Maybe if you tell a little bit more about your goal I can provide more input.

1 Like

Are you not trying to write an event bus? I quickly threw this together some time ago.
(I honestly have no idea if this is good written, it can be that some day I find another way to do this. Without the reflection)