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?
All classes have at least one constructor. If a class does not explicitly declare any, the Java compiler automatically provides a no-argument constructor, called the default constructor.
A constructor that takes no parameters is called a parameterless constructor. Parameterless constructors are invoked whenever an object is instantiated by using the new operator and no arguments are provided to new . For more information, see Instance Constructors.
If we don't define a constructor in a class, then the compiler creates a default constructor(with no arguments) for the class. And if we write a constructor with arguments or no arguments then the compiler does not create a default constructor.
But if you do type in a constructor within your class, you are not supplied a default constructor by the compiler. A default constructor is always a no-argument constructor, i.e. it accepts no arguments, and that's why it is known as default no-argument constructor.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With