jeudi 10 novembre 2016

Java Reflection with Child Classes

I'm attempting to use Reflections (as provided by org.reflections) to handle some heavy lifting, and so I don't need to manually create an instance for every class in a very long list. However, Reflections isn't targeting the classes in the way I'd expect, which is causing some issue.

My current Reflections code:

Reflections reflections = new Reflections(this.getClass().getPackage().getName() + ".command.defaults");
Set<Class<? extends Command>> commandClasses = reflections.getSubTypesOf(Command.class);

// Iterate through all the detected/found classes
for (Class c : commandClasses) {
    // If a class is abstract, ignore it.
    if (Modifier.isAbstract(c.getModifiers())) {
        continue;
    }

    // Attempt to create an instance of the class/command whatever.
    try {
        c.newInstance();
    } catch (InstantiationException | IllegalAccessException ex) {
        // For once, the right thing to do is just ignore the exception.
        // If a command is loaded but we can't create an instance or we
        // can't access it, just skip. But, we'll at least log it (for now).

        ex.printStackTrace();
    }
}

Essentially, my program has all commands present in com.example.command.defaults, where they're divided up into a number of sub-packages just for visual grouping. Each command is in its own class, where it extends one of our three abstract classes: PlayerCommand, SimpleCommand, or just Command. PlayerCommand and SimpleCommand also extend Command.

From my understanding, reflections.getSubTypesOf(Command.class) should allow me to target any class that extends Command in any way, but it doesn't seem to be working that way. Using my debugger tool, I've noticed that only a single class (which extends just Command) is actually being read by the system.

How can I make my Reflections code target all classes that extend Command and any classes that extend a class that extends Command?





Aucun commentaire:

Enregistrer un commentaire