jeudi 13 juin 2019

Creating a new instance of implemented class, based on argument class type

I'll shortly describe how my code structure looks like:

Class Aaa implements EventEmmiter

Class Bbb implements EventEmmiter

Class AaaEvent implements Event

Class BbbEvent implements Event

I want to create a "createSomething" method to avoid code duplication. I want this method to create, depended of argumentType (it can be Aaa or Bbb), a new instance of class which extends from Event.

Here is a not working sample cause we cannot create new Instance of Type. But I think that is shows what I want to achieve.

    public void createSomething(EventEmitter eventEmitter) {
        <T> someEvent = **new <? extends Event>** (eventEmitter);
    }

For example. If type of EventEmmiter passed as a method argument is Aaa i want to create a new AaaEvent instance.

Can you give me some tips how to implement such things?

Aucun commentaire:

Enregistrer un commentaire