简体   繁体   中英

How to check if a java class contain a default constructor?

I want to check if a Java class contains a default constructor.

Case 1:

public class ClassWithConstructor {

    //attributes...

    //default constructor
    public ClassWithConstructor(){}

}

Case 2:

public class ClassWithoutConstructor {

    //attributes...

    // no default constructor

}

In case 1, I want to print "ClassWithConstructor contains a default constructor."

In case 2, I want to print "ClassWithoutConstructor doesn't contain any default constructor" .

You can inspect your class via the Java Reflection API, there is a class called Constructor (see http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-frame.html ). Not sure, though, whether you can actually distinguish the Java default constructor and a parameterless one you defined on your own.

You can't check this case. The class without constructors creates a default constructor with the same attributes that a public ClassName(){} , nevertheless you can check if the modifier or attributes change.

If you debug this code, you will see that both Constructors[] have the same attributes except the clazz, they have the distinct name.

import java.lang.reflect.Constructor;

import org.junit.Test;

public class ScriptBuilderTest {

@Test
public void test()  {

    Class<ObjectWithDeclaredConstructor> ObjectWithDC = ObjectWithDeclaredConstructor.class;
    Class<ObjectWithoutDeclaredConstructor> ObjectWithoutDC = ObjectWithoutDeclaredConstructor.class;

    Constructor<?>[] ctorsWithDC = ObjectWithDC.getDeclaredConstructors();
    Constructor<?>[] ctorsWithoutDC = ObjectWithoutDC.getDeclaredConstructors();

    System.out.println("end");
}

public class ObjectWithDeclaredConstructor{
    public ObjectWithDeclaredConstructor(){}
}

public class ObjectWithoutDeclaredConstructor{  }
}

Case 1: In case 1, you don't have a default constructor. But in case 2, you have a default constructor. In case 1 the constructor is created by you, not by your compiler. In Java, the compiler is always responsible for creating a default constructor. In case 1 the compiler code looks like below.

public class ClassWithConstructor {


    public ClassWithConstructor(){
         super();//This code is generated by compiler
     }

}

S0 super() is generated by the compiler since the first line of the constructor should be this() or super() . Since it does not have anything I created super() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM