Object obj = new Object();
try {
obj.getClass().getConstructor();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
dosomething();
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
我不想像这样检查,因为它抛出异常.
还有另外一种方法吗?
Sot*_*lis 14
您可以获取所有Constructors并检查其参数数量,当您找到具有0的参数时停止.
private boolean hasParameterlessPublicConstructor(Class<?> clazz) {
for (Constructor<?> constructor : clazz.getConstructors()) {
// In Java 7-, use getParameterTypes and check the length of the array returned
if (constructor.getParameterCount() == 0) {
return true;
}
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
你必须使用getDeclaredConstructors()非公共构造函数.
改写Stream.
private boolean hasParameterlessConstructor(Class<?> clazz) {
return Stream.of(clazz.getConstructors())
.anyMatch((c) -> c.getParameterCount() == 0);
}
Run Code Online (Sandbox Code Playgroud)
如果您使用的是Spring,则可以使用ClassUtils.hasConstructor():
ClassUtils.hasConstructor(obj.getClass());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6104 次 |
| 最近记录: |