我有一个项目,它使用反射来加载一些类 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 对我来说似乎是不好的做法。
小智 0
我认为,有一个更好的解决方案,但我不确定你的默认构造函数是什么意思。如果你的构造函数有 1 个参数,而默认构造函数没有参数,那么你可以简单地这样做:
return moduleClass.getDeclaredConstructors()[0].getParameterCount()==1;
Run Code Online (Sandbox Code Playgroud)
这还假设您只声明了一个构造函数。
如果您有更多的构造函数,则必须检查整个数组(如果有您想要的构造函数)。
for(Constructor<?> constructor : moduleClass.getDeclaredConstructors()){
if(constructor.getParameterCount()==1 && constructor.getParameterTypes()[0] == Bot.class){
return true;
}
}
return false;
Run Code Online (Sandbox Code Playgroud)
如果您需要检查构造函数中的特定类型,此代码还可以处理,并且这是我能够编写的最干净的解决方案。
解释:
getDeclaredConstructors 返回特定类中的所有构造函数。然后检查每个构造函数(通过简单的 foreach 循环),如果它符合您的要求,则返回 true。您可以通过更改参数数量轻松地针对不同的构造函数修改它,然后通过调用 constructor.getParameterTypes() 检查每个参数是否具有正确的类型。
| 归档时间: |
|
| 查看次数: |
994 次 |
| 最近记录: |