[英]How to check if a java class contain a default constructor?
我想檢查 Java class 是否包含默認構造函數。
情況1:
public class ClassWithConstructor {
//attributes...
//default constructor
public ClassWithConstructor(){}
}
案例二:
public class ClassWithoutConstructor {
//attributes...
// no default constructor
}
在案例 1 中,我想打印"ClassWithConstructor contains a default constructor."
在情況 2 中,我想打印"ClassWithoutConstructor doesn't contain any default constructor"
。
您可以通過Java Reflection API檢查您的類,有一個名為Constructor
的類(請參閱http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-frame.html )。 但是,不確定您是否能夠真正區分Java默認構造函數和您自己定義的無參數構造函數。
你不能檢查這種情況。 沒有構造函數的類創建一個默認構造函數,其屬性與public ClassName(){}
,但是您可以檢查修飾符是否更改。
如果您調試此代碼,您將看到兩個Constructors []具有除clazz之外的相同屬性,它們具有不同的名稱。
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{ }
}
情況 1:在情況 1 中,您沒有默認構造函數。 但在情況 2 中,您有一個默認構造函數。 在情況 1 中,構造函數是由您創建的,而不是由您的編譯器創建的。 在 Java 中,編譯器始終負責創建默認構造函數。 在案例 1 中,編譯器代碼如下所示。
public class ClassWithConstructor {
public ClassWithConstructor(){
super();//This code is generated by compiler
}
}
S0 super()
由編譯器生成,因為構造函數的第一行應該是this()
或super()
。 因為它沒有我創建的任何東西super()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.