Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Parameterless constructor validation. Java

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading