Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check a class has no arguments constructor

    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?

like image 680
Q.yuan Avatar asked Jan 07 '15 02:01

Q.yuan


People also ask

Does every class have a no-argument constructor?

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.

Is a constructor with no arguments?

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.

What happens if your class doesn't have a no-argument constructor?

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.

What is no-argument constructor in C++?

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.


1 Answers

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);
}
like image 78
Sotirios Delimanolis Avatar answered Sep 28 '22 07:09

Sotirios Delimanolis