Manipulate all children of a given abstract parent class dynamically

Is there a way to dynamically create all the children of an abstract class?

What I currently have looks like this:

public class CommandHandler {

    private Command info        = new Info();
    private Command prefix      = new Prefix();
    private Command roll        = new Roll();
    private Command coin        = new Coin();
    private Command invite      = new Invite();
    private Command quit        = new Quit();
    private Command restart     = new Restart();

}

If the abstract parent class looks something like this:

public abstract class Command {

    protected String name;
    protected String arguments;

    protected abstract void execute();

}

But what if I want to create an instance of all the classes that extend the team without typing them all separately and adding them to the list every time I add a command?

And if I can create them dynamically, can I also manage them dynamically? those. Add each class to the list after creating it.

Or is there a better design to use that does what I want in a simpler way?

EDIT: @Ash IDE, . , , , -

classPathList.addAll(ClasspathHelper.forClassLoader());

classPathList.addAll(ClasspathHelper.forJavaClassPath());

, -!

+4
1

maven ( , : p), :

<dependency>
    <groupId>org.reflections</groupId>
    <artifactId>reflections</artifactId>
    <version>0.9.10</version>
</dependency>

, , ( ):

public class Loader {

    public static void main(String[] args) {
        try {
            Set<URL> classPathList = new HashSet<URL>();
            classPathList.addAll(ClasspathHelper.forClassLoader());
            Set<Class<? extends Command>> result = new Reflections(new ConfigurationBuilder().setScanners(new SubTypesScanner()).setUrls(classPathList)).getSubTypesOf(Command.class);

            List<Command> commands = new ArrayList<Command>();

            for (Class<? extends Command> c : result) {
                System.out.println(c.getSimpleName());
                commands.add(c.newInstance());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
+4

Source: https://habr.com/ru/post/1666916/


All Articles