How can I check if there is a parameterless constructor in a class?
I tried:
if (classToCheck.getConstructor() != null) {
//Yes, there is one.
} else {
//No, there isn't one.
}
But classToCheck.getConstructor() always returns true.
What am I doing wrong?
Edit.
private boolean hasNoArgConstructor(Class classToCheck) {
try {
if (classToCheck.getConstructor() != null) {
return true;
}
} catch (NoSuchMethodException e) {
System.out.println("Error");
}
return false;
}
So, the main idea of a method is to get true if there is a constructor in a class that takes no arguments.
>Solution :
Just remember that if you dont write any explicit constructor , the compiler will give you a no args constructor implicitly .
So : class without any constructor ==> become a class with one no argument constructor after compilation.
you can use this code :
if(Arrays.stream(classToCheck.class.getConstructors()).filter(constructor -> constructor.getParameterCount() == 0).count() == 1 )
System.out.println("exists");
else
System.out.println("not exists");