Search code examples
javapackage

Calling mulitple classes' method inside a package


I am writing a Minecraft mod. I've got multiple classes inside a package, which all have the public static register() method. Upon starting of the Minecraft Client, I am calling every classes' register() method.

There are two problems with my code:

  1. There are a lot of classes inside that package and having every single class inside the main class looks awful
  2. Adding new class inside the package does not automatically add the register()-part inside the main class and can be easily forgotten.

The question is now: is there any way to automatically call every classes' register() method inside the main class?

One of my ideas was to fetch every class inside the package using ClassLoader.getSystemClassLoader().getResourceAsStream and then Class.forName, which looks like an overkill to me.

I have never actually learned java and only got to know it through examples, so don't go too hard on me.


Solution

  • You could create your own annotation @ToRegister and use it in your classes:

    @ToRegister
    public class ToRegister1 {
    }
    

    Then use Reflections to find the classes as explained in this answer.