標籤:範圍 color 網上 包含 aml 不可 err lan tput
最近在學習JAVA知識,通過網上翻看資料,發現原先有的理解不深的東西,漸漸明白了些。對象的使用,在編寫軟體過程中是必不可少的,不知道大家有沒和我一樣,幾乎都是使用new來建立。那麼,問題來了,JAVA有幾種建立對象 的方式呢?
- 使用new關鍵字建立。
- 使用Class的newInstance()方法,比如Person類,建立對象可以使用,但是下面的兩種方式不能調用private建構函式,且構造對象的類中必須包含無參建構函式,否則會報錯。
public class person { /** * */ private static final long serialVersionUID = 10L; String name = "Jack"; public person(){ this.name = name + " ma"; System.out.println("construct Person"); } private person(int a,int b) { System.out.println("a:"+a+ " b:" + b); } @Override public String toString() { return name; } }方法一//這裡的testReflect為包名,Person類在此包下Class clazz = Class.forName("testReflect.person ");person p = (person ) clazz.newInstance();方法二person p =person .class.newInstance();
- 使用Constructor類的newInstance方法,此方法屬於反射,可以調用任何範圍的建構函式,private也可以,且建立對象的類建構函式可以任意。
//調用無參建構函式 ,方式一person p = person.class.getDeclaredConstructor().newInstance();//調用無參建構函式 ,方式二Constructor c1=person.class.getDeclaredConstructor();c1.setAccessible(true);person p=(person)c1.newInstance();
這裡大家思考下,在調用無參建構函式時,方式一和方式二有什麼區別? 大家應該看到了c1.setAccessible(true); 這句代碼吧,查看方法的定義包含如下:A value of true indicates that the reflected object should suppress Java language access checking when it is used,意思是為true的時候禁止驗證授權,換句話的理解就是,private的無參構造也可以調用。這就是方式一和方式二的區別,方式一若private範圍修飾,則會報錯。
//調用有參建構函式Constructor c1=person.class.getDeclaredConstructor(new Class[] {int.class,int.class});或Constructor c1=person.class.getDeclaredConstructor(int.class,int.class);
JAVA建立對象的五種方式