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?
You can get all Constructor
s 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);
}
If you are using Spring you can use ClassUtils.hasConstructor():
ClassUtils.hasConstructor(obj.getClass());
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);