0

Within my program I have these classes:

public class Zombie extends Monster
{
   public static String getType() {return "Zombie";}
}

public class Skeleton extends Monster
{
   public static String getType() {return "Skeleton";}
}

Somewhere in my program I want to maintain an List of all Monsters that exist in the program which currently I do like this:

public class MonsterLister
{
   //ArrayList to hold the monsters
   private static ArrayList<String> monsters = new ArrayList<>();

   public static void main(String[] args)
   {
      MonsterLister.add(Zombie.getType());
      MonsterLister.add(Skeleton.getType());
      //More code
   }

   public static void addMonster(String monster)
   {
      monsters.add(monster);
   }

   public static ArrayList<String> getMonsters()
   {
      return monsters;
   }
}

Further down the development road I will want to add more monsters which might look like this:

public class Spider extends Monster
{
   public static String getType() {return "Spider";}
}

Now i would go and add this to the main method, but I would like a way for the program to automatically populate the monster list. So instead of having to go to the main method every time I add a new monster and adding a method call for it I want the program to just use all available classes. Furthermore the list of methods in my main method seems somewhat sloppy.

I thought about having an eventListener in every monster class but I would still need to call the class to register the eventListener so I would still have to call every class separately. A static constructor in every class would also only trigger once a method inside the class is called.

Is this possible in Java?

Note: the code example above is not my actual program, but instead of trying to make the actual program understandable with only a few code pieces, I decided to come up with a different example!

  • It's not an easy task with built-in Java mechanisms. Take a look at this related post http://stackoverflow.com/questions/492184/how-do-you-find-all-subclasses-of-a-given-class-in-java – Kostas Kryptos Jan 03 '15 at 15:00
  • What about creating a custom constructor in the Monster class that calls `MonsterLister.addMonster(getType());` – ByteBit Jan 03 '15 at 15:42
  • @ByteBit would not work because I would have to call the constructor... – user3718550 Jan 03 '15 at 16:36

1 Answers1

1

There is an excellent library from Google called reflections.

You can do something like this to scan a set of packages for types which are subtypes of a given type:

Reflections reflections = new Reflections("com.my.pkg");
Set<Class<? extends Monster>> monsterTypes = reflections.getSubTypesOf(com.my.pkg.Monster.class);
Alex
  • 2,435
  • 17
  • 18