Reputation: 1456
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"
.
Upvotes: 4
Views: 1922
Reputation: 39
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()
.
Upvotes: 1
Reputation: 165
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{ }
}
Upvotes: 2
Reputation: 2298
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.
Upvotes: 2