3

I want to make API calls to a bunch of different API services. I have an abstract class called ApiService that contains common methods for each subclass. Every new API will have to inherit and implement these methods.

My question is: how can I go through all the subclasses of ApiService and call their methods?

Right now, I have a static array of all the services instantiated already (which means that new services must be manually added to the array) that looks something like this:

ApiService[] services = {new SubService1(), new SubService2(), ...};

I was wondering if there was a better way of doing this.

Andrew Hassan
  • 591
  • 2
  • 5
  • 15
  • 1
    I think this link will be useful. Check it please. [Question][1] [1]: http://stackoverflow.com/questions/492184/how-do-you-find-all-subclasses-of-a-given-class-in-java – zari Jul 05 '13 at 15:01

1 Answers1

1

You want to call a method on each instances of subclasses of an abstract class. There is no automatic way to find all the instances of a class anyway, so you need to manage the list of all instances yourself.

You have to do one of the following:

  • manage the list manually, that is add instances to the list when you create them
  • make that more automated, by adding the instance to a static list in the constructor of your base class ApiService. But it makes the base class aware of the list of its instances, and it seems to me a bit of a code smell.

There is another alternative, when you know the number of instances in your application in advance: use an Enum instead of an abstract class. Each Enum value is an instance of the class, and it can implement interfaces and methods, and each instance can override a method differently.

Cyrille Ka
  • 15,328
  • 5
  • 38
  • 58