JAVA建立對象的五種方式

來源:互聯網
上載者:User

標籤:範圍   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);
    • public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)                                      throws NoSuchMethodException,                                             SecurityException
      • Parameters:
        parameterTypes - the parameter array
        Returns:
        The Constructor object for the constructor with the specified parameter list 
        傳入參數為數組。

     

 

  • 使用Clone的方法:無論何時我們調用一個對象的clone方法,JVM就會建立一個新的對象,將前面的對象的內容全部拷貝進去,用clone方法建立對象並不會調用任何建構函式。要使用clone方法,建立對象的類必須實現Cloneable介面並實現其定義的clone方法。關於clone可參考我轉載的JAVA深複製與淺複製。
  • 使用還原序列化:當我們序列化和還原序列化一個對象,JVM會給我們建立一個單獨的對象,在還原序列化時,JVM建立對象並不會調用任何建構函式。為了還原序列化一個對象,對應類需實現Serializable介面,附上一段具體實現代碼。
    import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;public class People implements Serializable{    private String name;    public People(){        this.name = "6點A君";        System.out.println("construct people");    }    @Override    public String toString() {        return this.name;    }        public static void main(String[] args) {        People p = new People();        System.out.println(p);        ObjectOutputStream oos = null;        ObjectInputStream ois = null;        try {            FileOutputStream fos = new FileOutputStream("test.out");            oos = new ObjectOutputStream(fos);            oos.writeObject(p);            oos.close();        } catch (Exception e) {            e.printStackTrace();        }        People p1;        try {            FileInputStream fis = new FileInputStream("test.out");            ois = new ObjectInputStream(fis);            p1 = (People)ois.readObject();            System.out.println(p1);        } catch (Exception e) {            e.printStackTrace();        }    }}

     

JAVA建立對象的五種方式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.