0

I have a lot of classes in a package that all extend FooBar, and I wish to make an ArrayList<FooBar> variable.

So far, I have just been adding them one by one into the ArrayList on startup and I hate it, because I often forget to add it to the list.

Andry
  • 16,172
  • 27
  • 138
  • 246

1 Answers1

0

Sounds like Java to me. Getting all classes in a package is tricky, as you have to use the Java Reflection API. You could do this using Reflections (http://code.google.com/p/reflections/).

 Reflections reflections = new Reflections("my.project.prefix");

 Set<Class<? extends FooBar>> subTypes = reflections.getSubTypesOf(FooBar.class);
nils
  • 1,362
  • 1
  • 8
  • 15
  • Thank you, however, the part I am having troubles with is getting the ArrayList – user3580232 Apr 28 '14 at 18:26
  • Do you mean ArrayList or ArrayList>? Still not sure what exactly you are planning to do. – nils Apr 28 '14 at 19:01
  • All the classes in the package extend FooBar, and I have been adding them to the arraylist 1 by 1 as in `foobarArrayList.add(new SomeRandomClassThatExtendsFooBar());` but I want it to automatically add them to the ArrayList.. – user3580232 Apr 28 '14 at 19:07
  • Okay, using the above code (and assuming that each of the classes provde a default constructor) it would be something like `for (final Class extends FooBar> clazz : subTypes) {foobarArrayList.add(clazz.newInstance();}`. Keep in mind that this can already be considered as an ugly hack. It is not good coding style... – nils Apr 28 '14 at 19:51