我有一个项目,它使用反射来加载一些类 als 模块。这些模块可以有一个带有特定参数的构造函数。如果该构造函数存在,我想使用该构造函数创建该类的新实例,如果它不存在,我想使用默认构造函数。
现在我想知道如何检查该特定构造函数是否存在。到目前为止,我发现的唯一方法是这样做:
private boolean hasBotConstructor(final Class<?> moduleClass) {
try {
moduleClass.getDeclaredConstructor(Bot.class);
// Constructor exists
return true;
}
catch (NoSuchMethodException e) {
// Constructor doesn't exist
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
这有效,但使用 try/catch 对我来说似乎是不好的做法。