Object obj = new Object();
try {
obj.getClass().getConstructor();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
dosomething();
e.printStackTrace();
}
我不想这样检查,因为它会抛出异常。
还有别的办法吗?
最佳答案
您可以获取所有构造函数
并检查它们的参数数量,当您找到一个参数为 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;
}
对于非公共(public)构造函数,您必须使用 getDeclaredConstructors()
。
用 Stream
重写。
private boolean hasParameterlessConstructor(Class<?> clazz) {
return Stream.of(clazz.getConstructors())
.anyMatch((c) -> c.getParameterCount() == 0);
}
关于java - 我如何检查一个类没有参数构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27810634/