-1

In many programs I see that when I implement an interface and override the methods they are called on specific events (example: onActionListener). I need to know how to call the methods from all the class that implements that specific interface. Thanks ahead for the answers.

  • make an instance of the implemented class and call the overridden method for each class – noone Jun 16 '19 at 21:05
  • check this out : https://stackoverflow.com/questions/347248/how-can-i-get-a-list-of-all-the-implementations-of-an-interface-programmatically – Houssem Nasri Jun 16 '19 at 21:05
  • Would you, by any chance, be trying to ask about how to **fire an event**, i.e., invoke a particular event-handling method in one or more listener class instances? – Kevin Anderson Jun 16 '19 at 21:59
  • Possible duplicate of [How can I get a list of all the implementations of an interface programmatically in Java?](https://stackoverflow.com/questions/347248/how-can-i-get-a-list-of-all-the-implementations-of-an-interface-programmatically) – buræquete Jun 16 '19 at 23:34

1 Answers1

1

You can only call a method of a class if it is static. If it is not, you can only call the method of "an Object" (an instance of this class). Now, assume you have a bunch of objects and an interface called ActionListener with actionPerformed() method in it. In order to call the method you will have to check if this object implements ActionListener - has the actionPerformed() method. Then, cast it to action listener, and call the method.

Take a look at this example:

JButton b1 = new JButton();
JButton b2 = new JButton();
Object[] objects = { b1, b2 }; // Some objects
for (Object obj : objects) {
    if (obj instanceof ActionListener) { // Check if they implement action listener
        ActionListener objListener = (ActionListener) obj;
        objListener.actionPerformed(new ActionEvent(null, 1, "command"));
    }
}
George Z.
  • 6,643
  • 4
  • 27
  • 47
  • Yes I know but for example, when you mod a game you override methods provided by the api and the methods are called when they are implemented. I want to achieve this mechanic. – Francesco Greco Jun 16 '19 at 23:06