mardi 8 janvier 2019

How do I make a method that creates a new instance of a generic class specified by an abstract class?

I'm trying to instantiate and register listener classes in a loop, based on a list of event classes. I'm trying to use a list such as:

static final Class[] USER_EVENTS_HANDLED = {
    FirstEvent.class,
    SecondEvent.class
};

I have a bunch of listener classes, one for each:

FirstEventListener extends MyAbstractListener<T extends MyEvent>
SecondEventListener extends MyAbstractListener<T extends MyEvent>

I'm currently manually registering the event class and listener class explicitly:

eventManager.registerListener(FirstEvent.class, new FirstEventListener());
eventManager.registerListener(SecondEvent.class, new SecondEventListener());

I'm trying to not duplicate the event name twice, for maintainability. I build the name of the listener class from the event class and instantiate it, but I'm struggling to come up with the right way to create a new instance of the listener using that. First tried newInstance, but then realized generics had to be treated specially. I got something like this snippet of code from somewhere:

private static class ListenerGenerator<E> {
    E generateListener(Class<E> clazz, Constructor constructor) throws Exception {
        return (E) constructor.newInstance();
    }
}

So to make that work, I tried calling "getConstructor", along with some other approaches, but that keeps resulting in a NoSuchMethod error.

What's the simplest approach to accomplish my goal?





Aucun commentaire:

Enregistrer un commentaire