I have a project that uses reflection to load a few classes als modules. These modules can have a constructor with a specific parameter. If that constructor exists I want to create a new Instance of that class using that constructor, if it doesn't exist I want to use the default constructor.
Now I'm wondering how to check if that specific constructor exists. The only way I have found so far is doing it like this:
private boolean hasBotConstructor(final Class<?> moduleClass) {
try {
moduleClass.getDeclaredConstructor(Bot.class);
// Constructor exists
return true;
}
catch (NoSuchMethodException e) {
// Constructor doesn't exist
return false;
}
}
This works, but using try/catch seems like bad practice to me.
Aucun commentaire:
Enregistrer un commentaire