问题
Object obj = new Object();
try {
obj.getClass().getConstructor();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
dosomething();
e.printStackTrace();
}
I don't want check like this, because it throw a Exception.
Is there another way?
回答1:
You can get all Constructors and check their number of parameters, stopping when you find one that has 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;
}
You'd have to use getDeclaredConstructors() for non-public constructors.
Rewritten with Stream.
private boolean hasParameterlessConstructor(Class<?> clazz) {
return Stream.of(clazz.getConstructors())
.anyMatch((c) -> c.getParameterCount() == 0);
}
回答2:
If you are using Spring you can use ClassUtils.hasConstructor():
ClassUtils.hasConstructor(obj.getClass());
回答3:
You can create a method that loops the class's constructor and check if any has no-arg constructor.
boolean hasNoArgConstructor(Class<?> klass) {
for(Constructor c : klass.getDeclaredConstructors()) {
if(c.getParameterTypes().length == 0) return true;
}
return false;
}
Note that by using getDeclaredConstructors(), default constructor added by the compiler will be included. Eg following will return true
class A { }
hasNoArgConstructor(A.class);
You can use getConstructors() but it will only check visible constructors. Hence following will return false
boolean hasNoArgConstructor(Class<?> klass) {
for(Constructor c : klass.getConstructors()) {
if(c.getParameterTypes().length == 0) return true;
}
return false;
}
class B {
private B() {}
}
hasNoArgConstructor(B.class);
来源:https://stackoverflow.com/questions/27810634/how-can-i-check-a-class-has-no-arguments-constructor