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.You'd have to use
getDeclaredConstructors()
for non-public constructors.Rewritten with
Stream
.You can create a method that loops the class's constructor and check if any has no-arg constructor.
Note that by using
getDeclaredConstructors()
, default constructor added by the compiler will be included. Eg following will return trueYou can use
getConstructors()
but it will only check visible constructors. Hence following will return falseIf you are using Spring you can use ClassUtils.hasConstructor():