標籤:
雜談 |
1.new
通常都是使用java的關鍵字new來創建對象實例。
若有一個Something類,則可以通過下面的語句創建Something類的對象實例並指定到變量obj。
- Something somethingNew = new Something();
- Something somethingNew = new Something();
- Something somethingNew = new Something(); 通過new創建對象實例必須把類名寫在原代碼裏面。
2.clone
若程序寫成如下,則可以根據當前對象(this)建立一個新實例對象(沒有調用構造函數).
- public class Something implements Cloneable{
- private Something obj;
- public Something cloneSomething()
- {
- try {
- obj = (Something)this.clone();
- // obj = (Something)clone();
- } catch (CloneNotSupportedException e) {
- e.printStackTrace();
- }
- return obj;
- }
- }
- public class Something implements Cloneable{
- private Something obj;
- public Something cloneSomething()
- {
- try {
- obj = (Something)this.clone();
- // obj = (Something)clone();
- } catch (CloneNotSupportedException e) {
- e.printStackTrace();
- }
- return obj;
- }
- }
- public class Something implements Cloneable{
- private Something obj;
- public Something cloneSomething()
- {
- try {
- obj = (Something)this.clone();
- // obj = (Something)clone();
- } catch (CloneNotSupportedException e) {
- e.printStackTrace();
- }
- return obj;
- }
- } 如果需要複製上面的那個obj指向的對象實例時,調用somethingNew.cloneSomething()方法就ok了。
但是爲什麼不直接使用somethingNew.clone()呢?
JDK中Object# clone()方法的原型是:
protected native Object clone() throws CloneNotSupportedException;
方法修飾符是protected,而不是public。這種訪問的不可見性使得我們對Object#clone()方法不可見。
所以,必需重寫Object的clone方法後才能使用。
- public Object clone()throws CloneNotSupportedException
- {
- Something obj;
- obj= (Something)super.clone();
- return obj;
- }
- public Object clone()throws CloneNotSupportedException
- {
- Something obj;
- obj= (Something)super.clone();
- return obj;
- }
- public Object clone()throws CloneNotSupportedException
- {
- Something obj;
- obj= (Something)super.clone();
- return obj;
- }
值得注意的是:如果需要使用clone方法,必需實現java.lang.Cloneable接口,否則會拋出java.lang.CloneNotSupportedException。
另外clone方法所做的的操作是直接複製字段的內容,換句話說,這個操作並不管該字段對應的對象實例內容。
像這樣字段對字段的拷貝(field to field copy)就成爲"淺拷貝",clone方法所做的正是"淺拷貝".
3.newInstance
利用java.lang.Class類的newInstance方法,則可根據Class對象的實例,建立該Class所表示的類的對象實例。
創建Something類的對象實例可以使用下面的語句(這樣需要一個已經存在的對象實例)。
- somethingNew.getClass().newInstance().
- somethingNew.getClass().newInstance().
- somethingNew.getClass().newInstance(). 或者使用下面的語句(只需要存在相應的.class文件即可)
- Something instance = (Something) Class.forName("cn.softkid.test.Something").newInstance();
- Something instance = (Something) Class.forName("cn.softkid.test.Something").newInstance();
- Something instance = (Something) Class.forName("cn.softkid.test.Something").newInstance(); 如果包下不存在相應.class文件,則會拋出ClassNotFoundException。
注意 :newInstance創建對象實例的時候會調用無參的構造函數,所以必需確保類中有無參數的構造函數,否則將會
拋出java.lang.InstantiationException異常。無法進行實例化。