mercredi 7 juin 2023

Receiving a class implementation of a interface as a method argument

Is it possible to create a method who receives a Class implementation of an interface, but using the interface as argument and avoiding to receive the interface class.

I want to create an instance (and control it) of the interface implementation via reflection, so I need a valid class, not an interface class

for example:

interface MyInterface {}

class MyClass implements MyInteface{}


void myMethod(Class<? extends MyInterface> clazz){
    Constructor<MyInteface> constructor = (Constructor<MyInteface>) clazz.getConstructor();          
    MyInteface handler = constructor.newInstance();
}

This way works, but it also accept MyInterface.class as an argument, and I can't instantiate an interface.

myMethod(MyClass.class); // it's ok, what I want
myMethod(MyInterface.class); // this won't work - I want to avoid this case of use




Aucun commentaire:

Enregistrer un commentaire