(Java Reflection) Checking if a specific constructor exists

Viewed 1587

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.

1 Answers

I think, there is a better solution, but I am not sure what you mean with default constructor. If you have constructor with 1 parameter and default constructor has no parameters, than you can do it simply like this:

return moduleClass.getDeclaredConstructors()[0].getParameterCount()==1;

This also suppose, that you have only one constructor declared.

If you have more constructors, than you have to check the whole array, if there is the one, that you want.

for(Constructor<?> constructor : moduleClass.getDeclaredConstructors()){
       if(constructor.getParameterCount()==1 && constructor.getParameterTypes()[0] == Bot.class){
             return true;
       }
}
return false;

This code also handle, if you need to check for the specific type in the constructor and it's the cleanest solution I, that I were able to write.

EXPLANATION:

getDeclaredConstructors return all constructors in the specific class. Than you check each constructors (by simple foreach loop) and if it fits your requirements you return true. You can easily modify it for different constructors by changing the number of parameters and than checking, if each parameter has the correct type by calling constructor.getParameterTypes().

Related